Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 643
skellertor Avatar asked Apr 26 '21 21:04

skellertor


People also ask

How does Promise allSettled work?

The Promise.allSettled() method takes an iterable of promises as input and returns a single Promise . This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise.

Does Promise all always return same order?

Yes, the values in results are in the same order as the promises .

What is the difference between Promise all and Promise allSettled?

Promise.all() will reject immediately upon any of the input promises rejecting. In comparison, the promise returned by Promise.allSettled() will wait for all input promises to complete, regardless of whether or not one rejects. Use allSettled() if you need the final result of every promise in the input iterable.

Does Promise all resolve?

It returns a single Promise that resolves when all of the promises passed as an iterable, which have resolved or when the iterable contains no promises.


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.

like image 145
CertainPerformance Avatar answered Oct 30 '22 19:10

CertainPerformance