Will it catch?🤯
Omi

Omi @ompals

About: Software Engineer I am always curious, how developers make developers life easy! My favorite thing to do is, dive deep into a popular technology and get to know the "why" and "how" of it.

Location:
Surat, Gujarat, India
Joined:
Oct 27, 2020

Will it catch?🤯

Publish Date: Feb 22
3 2

Was just recovering from last Node.js blocking non-blocking stuff, I come to another JS injury called error-handling with promises.

This injury was again caused to me by not being able to distinguish between blocking and non-blocking code.

The below question is from javascript.info website.

What do you think? Will the .catch trigger? Explain your answer.

new Promise(function (resolve, reject) {
  setTimeout(() => {
    throw new Error("Whoops!");
  }, 1000);
}).catch(console.error);
Enter fullscreen mode Exit fullscreen mode

The hint: Look at the code like this:

new Promise(function (resolve, reject) 
// try {
{
  setTimeout(() => {
    throw new Error("Whoops!");
  }, 1000);
})
//} catch {
.catch(console.error);
// }
Enter fullscreen mode Exit fullscreen mode

Comment down your answer below!

Comments 2 total

  • Deep Gandhi
    Deep GandhiMar 23, 2025

    I thought the compiler would catch it, but when I ran it, the result differed from my expectation. Maybe it's because the error is in a different scope inside setTimeout? 🤔

    • Omi
      OmiMar 23, 2025

      The main thread execution looks something like this:

      new Promise(function (resolve, reject) 
      try {
        // Register a setTimeout I/O
      } catch(e) {
      console.error(e.message);
      }
      
      // After 1 second
      throw new Error("Whoops!");
      
      Enter fullscreen mode Exit fullscreen mode

      The throw error statement will hang outside try...catch guards when defined in a callback of an async operation.

Add comment