Search code examples
javascriptfetch-api

run multiple fetch calls in order


I have an array of sizes that I am looping through in order to run a fetch api call with the size as a parameter of the url. The issue I am having is that I would like run the api calls in order and push the response up to a bigger array so that all the data is collated together. I cant seem to push this response data up to the array in the order of the original size array. My code currently looks like this:

sizeOptionsArr.forEach((option, index) => {
  const storeAPI = `https://api-url/json/store-stock-lookup?productCode=${option}`
  return fetch(storeAPI)
    .then((res) => res.json())
    .then((data) => {
      fullDataArr.push(data.data)
      console.log(index)
    })
})

When I console log the index this appears in a random sequence every time which suggests that the api calls are all running in sync or in a random order.

Any help would be really appreciated. Thanks in advance.


Solution

  • You can make use of Promise.all to run the API requests in parallel and still get the responses in order.

    const promises = sizeOptionsArr.map((option) => {
      const storeAPI = `https://api-url/json/store-stock-lookup?productCode=${option}`
      return fetch(storeAPI)
        .then((res) => res.json())
        .then((data) => data.data)
    });
    
    Promise.all(promises)
      .then((responses) => {
        fullDataArr.push(...responses)
      });