Skip to content

Instantly share code, notes, and snippets.

@mafintosh
Last active March 30, 2022 06:30
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mafintosh/d18db4daea7910c16137a053b3b513b1 to your computer and use it in GitHub Desktop.
Save mafintosh/d18db4daea7910c16137a053b3b513b1 to your computer and use it in GitHub Desktop.
promise-unhandled-why.js
start()
async function start () {
const promises = [
new Promise((resolve, reject) => setTimeout(reject, 1000)),
Promise.reject(),
Promise.reject()
]
for (const a of promises) {
try {
await a
} catch {
console.log('failed, continuing')
}
}
}
@vikasg603
Copy link

vikasg603 commented Jul 13, 2021

Your line number 6 and 7 is what caused an unhandled promise.
Promise.reject() -> new rejected promise.
so it is returning a new promise and also rejecting that promise.

And because you don't have a catch statement, it is an unhandled promise.

Your new code with no rejected promise.

start()

async function start () {
  const promises = [
    new Promise((resolve, reject) => setTimeout(reject, 1000)),
    Promise.reject().catch(()=> {}),
    Promise.reject().catch(()=> {})
  ]

  for (const a of promises) {
    try {
      await a
    } catch {
      console.log('failed, continuing')
    }
  }
}

Reason No handled promise error on line number 5:
as we all know, javascript is asynchronous.
On line number 5, it will not wait for the timeout but rather pass that to the system (native methods).
As we don't have any CPU-intensive tasks, javascript will not take more than 50ms (It may be less) to run the execution of the complete start function.

While running the function, you have already given the await statement to your timeout promise, which means handling it. As await can have try-catch, so after 1 minute, it rejects that promise, but we have already provided the handler, so it is not an unhandled promise, and we are getting failed, continuing on the console.

But even if we have a 1 ms timeout on our promise, javascript will handle that because javascript can't perform anything in parallel, so it will handle the timeout part only after executing the complete start function.

This is why we don't add CPU-intensive tasks on the main thread, as it can even block timeout (just 1 example).

@vikasg603
Copy link

And 1 thing, I also noticed.
Your unhandled promise will be gone after 1 sec.
I assumed that after 1 sec, for loop handling them (1 sec for timeout).
So as soon as they got handler, unhandled promise gone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment