Is the Result of JavaScript Promise.all() Ordered?

The order of the results returned by the JavaScript Promise.all() method is guaranteed to be the same as the order of the promises passed to it. This means that if you pass an array of promises to Promise.all(), the resulting array of values will be in the same order as the original array of promises.

For example:

const promises = [
  Promise.resolve(1),
  Promise.resolve(2),
  Promise.resolve(3)
];

Promise.all(promises)
  .then(values => console.log(values)); // [1, 2, 3]

As you can see, the output of the code above is [1, 2, 3], which is in the same order as the original array of promises.

However, when a Promise in Promise.all() is rejected, the resulting Promise (returned by Promise.all()) is immediately rejected with the same error. In such case, the following holds true:

  1. Any promises that have already resolved or pending are ignored;
  2. The "then()" callback is not called at all. Instead, the "catch()" callback is called with the error passed as an argument.

For example:

const promises = [
  Promise.resolve('one'),
  Promise.reject('Error occurred'),
  Promise.resolve('two')
];

Promise.all(promises)
  .then(values => console.log(values))
  .catch(error => console.log(error)); // 'Error occurred'

In the example above, the then() callback is not called at all, instead the catch() callback is called, which logs the error message to the console.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.