Thorben Bochenek Thorben Bochenek - 2 years ago 132
Javascript Question

Promise.all: Order of resolved values

Looking at MDN it looks like the

passed to the
callback of Promise.all contains the values in the order of the promises. For example:

var somePromises = [1, 2, 3, 4, 5].map(Promise.resolve);
return Promise.all(somePromises).then(function(results) {
console.log(results) // is [1, 2, 3, 4, 5] the guaranteed result?

Can anybody quote a spec stating in which order
should be in?

PS: Running code like that showed that this seems to be true although that is of course no proof - it could have been coincidence.

Nit Nit
Answer Source

Following the spec you linked to, Promise.all(iterable) takes an iterable (that is, an object that supports the Iterator interface) as a parameter and later on calls PerformPromiseAll( iterator, constructor, resultCapability) with it, where the latter loops over iterable using IteratorStep(iterator).
This means that if if the iterable you pass in to Promise.all() is strictly ordered, they will still be ordered once passed in.

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 that the output is strictly ordered as the input as long as the input is strictly ordered (for example, an array).

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

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

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download