Imagine that we define a function that can do a unit of work some time later called doSomeAsyncWork.
You pass it how long you want to wait before doing the work and a 'work' function which receives both
resolve and reject...
var doSomeAsyncWork = function (timeMs, work) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
work(resolve, reject);
}, timeMs);
});
};Now we ask it to do some async work, but in the process we make a mistake and throw...
doSomeAsyncWork(1000, function (resolve, reject) {
throw Error("Oh noes!");
}).catch(function (e) {
console.log('caught async work rejection');
});Will the console log 'caught async work rejection'? Why/why not?
The above fails for the same reason:
…doesn't work. The function passed to
setTimeoutthrows, but thetry/catchis no longer in the stack, as it's executed as part of a separate task.A better way (IMO) to implement what you're trying to do is:
Then:
And this works as expected: