let result;
try {
result = Promise.resolve(func());
} catch (error) {
result = Promise.reject(error);
}Promise.try() / notebook
Promise.try()
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
new Promise((resolve) => resolve(func()));Promise.try(func);Promise.resolve().then(func);Promise.try(() => func(arg1, arg2));Promise.try(func, arg1, arg2);function doSomething(action) {
return Promise.try(action)
.then((result) => console.log(result))
.catch((error) => console.error(error))
.finally(() => console.log("Done"));
}
doSomething(() => "Sync result");
doSomething(() => {
throw new Error("Sync error");
});
doSomething(async () => "Async result");
doSomething(async () => {
throw new Error("Async error");
});async function doSomething(action) {
try {
const result = await action();
console.log(result);
} catch (error) {
console.error(error);
} finally {
console.log("Done");
}
}Promise.try = function (func, ...args) {
let result;
try {
result = func(...args);
} catch (error) {
return Promise.reject.call(this, error);
}
return Promise.resolve.call(this, result);
};class NotPromise {
constructor(executor) {
// The "resolve" and "reject" functions behave nothing like the native
// promise's, but Promise.try() just calls resolve
executor(
(value) => console.log("Resolved", value),
(reason) => console.log("Rejected", reason),
);
}
static try = Promise.try;
}
const p = NotPromise.try(() => "hello");
// Logs: Resolved hello
// p is a NotPromise instance
const p2 = NotPromise.try(() => {
throw new Error("oops");
});
// Logs: Rejected Error: oops
// p2 is a NotPromise instance