'using try catch on error generated by asynchronous callback function [duplicate]
I am trying to catch an error caused by an async javascript callback function,
try{
setTimeout(()=>{
throw err
console.log("after throw")
}, 1000)
}catch(e){
console.log("caught");
}
But as many of you may know catch block is never executed, so what exactly is happening here?
I know I can achieve similar thing using promises and async/await,
async foo(){
try{
await setTimeoutPromise(1000);
}catch(e){
alert("caught");
}
}
Solution 1:[1]
These are two different things.
The first code won't catch the error, since it happens asynchronously, and try...catch will only catch synchronously thrown exceptions.
The second code will catch the error, because await 'synchronize' the code (makes it look and work like it would've been synchronous), and the error thrown only by await: if you haven't been used it, you would get only a rejected promise (You can't really throw anything from an async function!)
To make the first code working, move the try...catch inside the callback:
setTimeout(()=>{
try{
throw err
}catch(e){
console.log('catched')
}
console.log("after throw")
}, 1000)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
