Skip to main content

Unexpected Promise.all() fail fast behavior - continues to execute after rejection

From MDN:

Promise.all is rejected if any of the elements are rejected. For example, if you pass in four promises that resolve after a timeout and one promise that rejects immediately, then Promise.all will reject immediately.

Let's discuss the following code snippet:

(async () => {
    try {
    const awaited = await Promise.all([
        (() => {
            console.log('1');
            return Promise.reject('2');
        })(),
        (() => {
            console.log('3');
            return Promise.resolve('4');
        })(),
    ]);

    console.log(awaited);
    } catch (error) {
    console.log(error);
    } finally {
    console.log('5');
    }
})();

All the promises in the code above are immediately resolved/rejected. I think that the code should execute this way:

  1. First console.log is executed, thus logging '1';
  2. Promise is rejected with the value '2' thus fast-failing Promise.all();
  3. 'Catch' clause is executed, logging the rejected value of '2';
  4. 'Finally' clause is executed regardless, logging '5';

Instead, I see a '3' also being logged. Why is it so?

Via Active questions tagged javascript - Stack Overflow https://ift.tt/jCpNVUh

Comments