Does Promise.allSettled preserve the original order in the response in all scenarios?

Viewed 2367

When making multiple requests concurrently with Promise.allSettled, does the order of the array in the response correspond to the intitial array in the request? Does it maintain the same order regardless of the order in which they settle?

const promise1 = new Promise((resolve, reject) => setTimeout(resolve, 2000, 1)); //finish last
const promise2 = Promise.resolve(2); //finish first
const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 100, 3)); //finish in the middle

const promises = [promise1, promise2, promise3];

Promise.allSettled(promises).
  then((results) => results.forEach((result) => console.log(result)));

In testing it seems to be true, but there seems to be no guarantee in the documentation that the order will remain. The MDN docs are here

1 Answers

Yes, it is guaranteed. The steps are described in the specification.

On each iteration over the passed iterable, it does

Set resolveElement.[[Index]] to index. Set rejectElement.[[Index]] to index.

where index is the current index in the iterable being iterated over, which then gets passed to the resolver or rejector algorithm. Both the resolver and the rejector does, at the end:

Set values[index] to obj.

where values is the array of resolve values that the whole Promise.allSettled will resolve with.

The nth item in the passed iterable/array will always correspond to the nth item in the resolved array.

Related