Search code examples
javascriptecmascript-6ecmascript-5

using try catch on error generated by asynchronous callback function


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

  • When you use setTimeout, the callback gets pushed into the event loop (moved out of the JS Engine and into the realm of the runtime/browser) and your foo function exits immedeatly.

    After the timeout AND once the stack is empty, the event loop will put the callback onto the stack and run it. That's why the try/catch and the callback are independent of each other. That's also why setTimeout(1000) does not mean in a second but not earlier than and somewhat close to one second.

    See What the heck is the event loop anyway? | Philip Roberts | JSConf EU