I'm trying to understand how to use try/catch when it comes 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);
}
The 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);
}
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With