I'm trying to understand how to use try/catch when it es to nested callbacks. Why doesn't this piece of code catch my new error ?
function test(cb) {
setTimeout(function() {
throw new Error("timeout Error");
}, 2000);
}
try {
test(function(e) {
console.log(e);
});
} catch (e) {
console.log(e);
}
I'm trying to understand how to use try/catch when it es to nested callbacks. Why doesn't this piece of code catch my new error ?
function test(cb) {
setTimeout(function() {
throw new Error("timeout Error");
}, 2000);
}
try {
test(function(e) {
console.log(e);
});
} catch (e) {
console.log(e);
}
Share
Improve this question
edited Oct 21, 2016 at 14:16
user3589620
asked Oct 21, 2016 at 14:05
runners3431runners3431
1,4551 gold badge13 silver badges31 bronze badges
2 Answers
Reset to default 10The error happens asynchronously, when the function passed to setTimeout
runs. By the time the error is thrown, the test
function has already finished executing.
There are many ways to set a timer for Javascript execution. Here's one way that uses Promise.race():
(async () => {
try {
await Promise.race([
// Timer.
new Promise((res, rej) => {
setTimeout(() => {
rej("Timeout error!");
}, 2000);
}),
// Code being timed.
new Promise((res, rej) => {
// Do some stuff here.
// If it takes longer than 2 seconds it will fail.
res("Finished in under 2 seconds.");
})
]);
} catch (err) {
console.log("we got an err: " + err);
}
})();