Currently, I\'m trying to decide what pattern I should use while dealing with errors inside a Promise. For instance, I have the code below
promiseFunc()
.the
What approach should be used to reject the Promise if a function inside it (setTimeout(), in my case) throws an Error
An asynchronous callback must never throw an exception. Your function that you try to promisify (setTimeout) either throws a synchronous exception (which new Promise handles), or it calls the callback. In the callback you must call resolve or reject, and do so without throwing an exception.
If you want to do additional things in the callback (besides calling resolve/reject), things that could throw an exception: don't!
The new Promise should wrap only the immediate function that you want to promisify, nothing else. Do more things in then callbacks that are chained to the promise - then will handle exceptions in its callback just fine:
function promiseFunc() {
return new Promise(resolve => {
setTimeout(resolve, 1000);
// ^^^^^^^ nothing can go wrong in here
}).then(() => {
throw "setTimeout's callback error";
// ^^^^^ here, it will lead to a rejection
return "resolution";
});
}