-1

QUESTION:

After looking at this:

Promise.all: Order of resolved values

I am not certain it applies to my case. Will responses always be in the same order as urls ?


CODE:

var urls = [];

for (var i = 0; i < enemies.length; i++) {
     urls.push('someURL/'+enemies[i].id);
}

let promises = urls.map(url => fetchJSON(url, region));

Promise.all(promises).then(responses => {
      //DO SOMETHING HERE WITH RESPONSES WHERE ORDER IS IMPORTANT
});


function fetchJSON(url, region) {
    return fetch(url, {
        region: region,
        headers: { 
            'token': apiKey
        }
    }).then(response => response.json());
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
TheProgrammer
  • 1,409
  • 4
  • 24
  • 53

3 Answers3

2

Yes, that's one of the guarantees that Promise.all provides. From MDN's page on Promise.all:

Return value

  • ...
  • ...
  • A pending Promise in all other cases. This returned promise is then resolved/rejected asynchronously (as soon as the stack is empty) when all the promises in the given iterable have resolved, or if any of the promises reject. See the example about "Asynchronicity or synchronicity of Promise.all" below. Returned values will be in order of the Promises passed, regardless of completion order.

(my emphasis)

(Also covered by the spec of course, but...the spec is tricky to read.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

TL;DR: yes.

Explanation:

Array.map returns an array of promises, the index of each promise in the array corresponds to the index of the URL in urls array.

Promise.all returns an array of the result of resolves of the promises array, the index of each result in the responses corresponds to the index of the corresponding promise in promises array.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92
1

Check the documentation

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all#Return_value

Returned values will be in order of the Promises passed, regardless of completion order.

So the answer is yes. Also, it would be trivial to contrive a test using setTimeout and independently verify that order is maintained.

Jed Richards
  • 12,244
  • 3
  • 24
  • 35