I am trying to re-create bluebird's promise.try function, is this essentially the same?
function promiseTry(callback) {
let error;
let value;
try {
value = callback();
} catch (e) {
error = e;
}
return new Promise((resolve, reject) => {
if (error) {
reject(error);
throw error;
}
resolve(value);
});
}
const x = promiseTry(() => {
throw new Error('hi');
});
How can I simply implement bluebird's Promise.try
with a native node Promise?
This should be equivalent:
function promiseTry(callback) {
return new Promise((resolve, reject) => {
try {
resolve(callback())
} catch(e) {
reject(e);
}
});
}
const x = promiseTry(() => {
throw new Error('hi');
});
x.then(() => console.log("Promise resolved")).catch(err => console.log("Promise rejected:", err.message));
If you can use async/await
, async function
s have this behavior implicitly. Any synchronous exceptions thrown in an async function are converted into a promise rejection.