Search code examples
javascriptes6-promise

Promises with ES6 destructuring fails when one of the promises don't succeed


There are a tons of topics about it but I couldn't find this case. Let me explain:

const [call1, call2, call3] = await Promise.all([promise1, promise2, promise3]);

If they succeed it should return allright, yes? But what if it fails? It throws me this: Unhandled Rejection (TypeError): (intermediate value) is not iterable

I could make it const calls = await.Promise.all(promises) then use it like calls[0] but is it possible any other way?


Solution

  • Awaiting a promise that will reject will cause the function to throw an exception. You handle that with a try-catch.

    try {
      const [call1, call2, call3] = await Promise.all([promise1, promise2, promise3]);
    } catch (error) {
      // Assuming the rejection value is an Error instance.
      const message = error.message
    }