0

Found pretty strange behavior of Javascript Promise.all() when catch() method fires after first single promise and before all others. Did anyone found such strange thing before? I'm wondering what's happening behind this?

let promises = [];
[1, 2, 3].forEach((value) => {
    const promise = new Promise((s, e) => {
        setTimeout(() => {
            e('Single Catch ' + value);
        }, Math.random() * 100);
    }).catch((err) => {
        console.log(err);
        return Promise.reject(err);
    });
    promises.push(promise);
});
Promise.all(promises).catch((err) => {
    console.log('All Done');
});

Expected result would be:

- Single Catch X
- Single Catch X
- Single Catch 1
- All Done

Bu instead we get:

- Single Catch X
- All Done
- Single Catch X
- Single Catch X
nostop
  • 743
  • 5
  • 9

1 Answers1

2

As per docs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

it rejects when any one of the first promise rejects.

so when your one catch block returns a rejected promise, the Promise.all is all done.

aas2909
  • 136
  • 4
  • The fun thing happens when you remove setTimeout. Then all catch block fires after all other promise catch blocks as I was expecting. So the behavior is not very consistent I guess due to some architecture issues. – nostop Jan 31 '19 at 16:15
  • @nostop If you remove the timeout, they all reject in the same event loop. With timeout, they all reject in subsequent event loops, but `Promise.all` doesn't wait until those happen and rejects in the first event loop where any of the promises reject. – deceze Jan 31 '19 at 16:18