简体   繁体   English

使用上次运行的回调响应多次调用异步函数

[英]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.可以使用async/await语法轻松完成。 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
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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