1

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.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
user16732475
  • 15
  • 1
  • 6
  • Would this answer your question? https://stackoverflow.com/questions/24586110/resolve-promises-one-after-another-i-e-in-sequence – Nikita Chayka Apr 28 '23 at 14:11
  • What you actually want to use is `Promise.all`, which collects the results in the expected order. And still allows the requests to run concurrently. – Bergi Apr 28 '23 at 14:11

1 Answers1

0

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)
  });
vighnesh153
  • 4,354
  • 2
  • 13
  • 27