简体   繁体   中英

Calling async function multiple times with callback response of previous run

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 }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM