1

I need to run a function for each item of the array... The problem is, for each run (except the first), the response from the previous run is supposed to be one of the parameters... How do I make sure the next iteration of the function isn't executed till the response from the last one is in place?

I am currently doing it as something like this, but no success:

array --> array with n items
callResponse --> array with (n-1) items
callResponse[0] is a required parameter for the function executing for array[1] and so on....

array = [ ........ ]
callResponse = [....empty x (n-1)....]

for (var i in array) {
var body = {
            parameter1: array[i],
            parameter2: i = 0 ? '' : callResponse[i-1],
           }
axios.get('', body).then((response) => { callResponse[i] = response.data.x }
}
hungary
  • 41
  • 3
  • do you also need to so something when all the iteration have competed ? – vaira Oct 15 '21 at 15:30
  • 1
    This should help you out https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – vaira Oct 15 '21 at 15:31

1 Answers1

0

It can easily be done with async/await syntax. Just wait until the request finishes then continue the next request:

(async () => { // await keyword only accept in an async function
  const array = [];
  const result = [];

  for (const item of array) { // for..of instead of for..in
    const body = {
      parameter1: item,
      parameter2: result[result.length - 1] || '', // get the last response
    };

    const res = await axios.post('url', body); // wait...
    result.push(res.data.x); // save the response and continue
  }

  console.log('Result: ', result); // all responses
})();
hoangdv
  • 15,138
  • 4
  • 27
  • 48