Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise.all: Order of resolved values

People also ask

Does promise all resolve in order?

While you'll get the resolution in the same order, there's no guarantee about when the promises are acted on. In other words, Promise. all can't be used to run an array of promises in order, one after the other.

Does promise all run sequential?

all() method executed by taking promises as input in the single array and executing them sequentially.

What is the result of promise all?

The Promise. all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will fulfill when all of the input's promises have fulfilled, or if the input iterable contains no promises.

Is promise all sequential or parallel?

Final Thoughts: Parallel ProcessingOften Promise. all() is thought of as running in parallel, but this isn't the case. Parallel means that you do many things at the same time on multiple threads. However, Javascript is single threaded with one call stack and one memory heap.


Shortly, the order is preserved.

Following the spec you linked to, Promise.all(iterable) takes an iterable as a parameter and internally calls PerformPromiseAll(iterator, constructor, resultCapability) with it, where the latter loops over iterable using IteratorStep(iterator).

Resolving is implemented via Promise.all() Resolve where each resolved promise has an internal [[Index]] slot, which marks the index of the promise in the original input.


All this means the output is strictly ordered given the iterable you pass to Promise.all() is strictly ordered (for example, an array).

You can see this in action in the below fiddle (ES6):

// Used to display results
const write = msg => {
  document.body.appendChild(document.createElement('div')).innerHTML = msg;
};

// Different speed async operations
const slow = new Promise(resolve => {
  setTimeout(resolve, 200, 'slow');
});
const instant = 'instant';
const quick = new Promise(resolve => {
  setTimeout(resolve, 50, 'quick');
});

// The order is preserved regardless of what resolved first
Promise.all([slow, instant, quick]).then(responses => {
  responses.map(response => write(response));
});

As the previous answers have already stated, Promise.all aggregates all resolved values with an array corresponding to the input order of the original Promises (see Aggregating Promises).

However, I would like to point out, that the order is only preserved on the client side!

To the developer it looks like the Promises were fulfilled in order but in reality, the Promises are processed at different speeds. This is important to know when you work with a remote backend because the backend might receive your Promises in a different order.

Here is an example that demonstrates the issue by using timeouts:

Promise.all

const myPromises = [
  new Promise((resolve) => setTimeout(() => {resolve('A (slow)'); console.log('A (slow)')}, 1000)),
  new Promise((resolve) => setTimeout(() => {resolve('B (slower)'); console.log('B (slower)')}, 2000)),
  new Promise((resolve) => setTimeout(() => {resolve('C (fast)'); console.log('C (fast)')}, 10))
];

Promise.all(myPromises).then(console.log)

In the code shown above, three Promises (A, B, C) are given to Promise.all. The three Promises execute at different speeds (C being the fastest and B being the slowest). That's why the console.log statements of the Promises show up in this order:

C (fast) 
A (slow)
B (slower)

If the Promises are AJAX calls, then a remote backend will receive these values in this order. But on the client side Promise.all ensures that the results are ordered according to the original positions of the myPromises array. That's why the final result is:

['A (slow)', 'B (slower)', 'C (fast)']

If you want to guarantee also the actual execution of your Promises, then you would need a concept like a Promise queue. Here is an example using p-queue (be careful, you need to wrap all Promises in functions):

Sequential Promise Queue

const PQueue = require('p-queue');
const queue = new PQueue({concurrency: 1});

// Thunked Promises:
const myPromises = [
  () => new Promise((resolve) => setTimeout(() => {
    resolve('A (slow)');
    console.log('A (slow)');
  }, 1000)),
  () => new Promise((resolve) => setTimeout(() => {
    resolve('B (slower)');
    console.log('B (slower)');
  }, 2000)),
  () => new Promise((resolve) => setTimeout(() => {
    resolve('C (fast)');
    console.log('C (fast)');
  }, 10))
];

queue.addAll(myPromises).then(console.log);

Result

A (slow)
B (slower)
C (fast)

['A (slow)', 'B (slower)', 'C (fast)']

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

One might cite the ES6 spec on Promise.all, though it's a bit convoluted due to the used iterator api and generic promise constructor. However, you'll notice that each resolver callback has an [[index]] attribute which is created in the promise-array iteration and used for setting the values on the result array.