Skip to content Skip to sidebar Skip to footer

Catching All Promise Rejections In An Async Function In Javascript

I've ran into an issue with catching all the errors when multiple promises throw rejection errors after being awaited in an async function (javaScript - node v8.4.0). Make referenc

Solution 1:

If both promises reject, then asyncParallel() logs an uncaught error with the promise that rejects last.

Yes - you created the timeoutTwo() promise but never handled its errors (like using it in an await). The await res2 was never executed due to the exception in await res1.

(Notice it's not "the promise that rejects last", but always the promise that is awaited second).

Is that because there is no built in mechanism for async function's try / catch blocks to catch multiple rejections in this way?

In sequential code, there cannot be multiple exceptions, so coming up with extra syntax to deal with them would be hard.

Do I still need to use a Promise.all inside async functions to make sure that the errors are handled correctly?

Yes, exactly that. If you want to wait for multiple promises in parallel, you should always use Promise.all. The await keyword is just sugar for the following .then() call.

You should write

asyncfunctionasyncParallel() {
  try {
    let [val1, val2] = awaitPromise.all([timeoutOne(), timeoutTwo()]);
    console.log(`All done with ${val1}${val2}`)
  } catch(err) {
    console.log(err)
  }
}

In both cases only the promise that returns first logs an error. I know that in some promise libraries there is a way to log all the errors (for example the "settle" method in bluebird), however, I'm not sure if there is an analogue to this method in native promises?

No, there's not. The characteristics of settle are trivial to implement yourself using then, with any values you desire:

asyncfunctionasyncParallel() {
  try {
    let [stat1, stat2] = awaitPromise.all([
        timeoutOne().then(() =>"one fulfilled", () =>"one rejected"), 
        timeoutTwo().then(() =>"two fulfilled", () =>"two rejected")
    ]);
    console.log(`All settled with ${stat1}${stat2}`)
  } catch(err) {
    console.log(err)
  }
}

Post a Comment for "Catching All Promise Rejections In An Async Function In Javascript"