Diving into Promises, I found something that confused me for a second. However, I realized what’s happening and decided to share it here for others who might bump into it.
I have the following JavaScript:
new Promise(function (resolve, reject) {
foo();
setTimeout(function () {
resolve();
}, 400);
}).catch(function (err) {
console.log('Caught it:', err.message);
});
When I run it, I get:
Caught it: foo is not defined
Which is the expected result. However, if I try to call foo()
in the setTimeout
callback like this:
new Promise(function (resolve, reject) {
setTimeout(function () {
foo();
resolve();
}, 400);
}).catch(function (err) {
console.log('Caught it:', err.message);
});
I get:
ReferenceError: foo is not defined at Timeout._onTimeout (C:\Users\Hristiyan\Desktop\promise.js:3:13) at tryOnTimeout (timers.js:224:11) at Timer.listOnTimeout (timers.js:198:5)
Question: Why don’t I get the same result? Why doesn’t the handler defined with catch()
handle the error? I mean, the error occurs under the same code block?