0

I have a structure like this:

methods: {
  function() {
    //some stuff in here    

    for(let i=0; i < array.length; i++) {
      //Problem in here or around here
      //in here I send something to my API and want to get data back
    }
  }
}

Explenation what I do: I have an array where I want to loop, for every loop I send data to my API and get data back inside the for-loop.

My problem: I always get the data back in different order because one ot the data is probably bigger and than it takes longer than the others.

Example: I send Array = [1,2,3,4] and want to get it back in the correct order. But 1 needs more time than 2,3,4 and I get than data back in order [2,3,4,1].

How can I assign my for-loop to wait till the first data is back and than go on?

Thank You!

patrick96
  • 175
  • 2
  • 14

1 Answers1

3

As soon as you've read up on async/await, you'll still wanna run your requests in parallel to save time, rather than sequentially. Promise.all helps here:

async function fetchData () {

  const resultsInOrder = await Promise.all(
    // pass an array of Promises
    array.map(element =>
      fetch(/* some arguments based on the element's data */)
        .then(res => res.json())
    )
  )
  // do something with results
}
DustInComp
  • 1,742
  • 8
  • 18