Search code examples
javascriptnode.jspromisefetch-api

Will the order of responses be the same as the order of the urls in my case?


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());
}

Solution

  • 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.