使用foreach遍历调用异步功能,返回结果,并且请求不正常



<!-- begin snippet: js hide: false console: true babel: false -->
async function query(num) {
  let data = await request(url, {num})
  console.log(num, data)
}
  [1, 2].forEach(function(item){
    	let _self = this
    	(function(item) {
        setTimeout(() => {
            _self.query(item)
            console.log(item)
        }, i)
      })(item)
  })
// if the server response
server.get('*', function(req, res) {
	let num = req.num
	res.send(num)
})

异步查询响应是: //1,2 //2,1

但是期望回应是 //1,1 //2,2如何获得理想的结果?请求参数如何与返回结果一致?

听起来您想执行Queries 串行,而不是并行。因此,每次迭代的开始都应在开始之前等待上一个迭代的分辨率。将awaitfor..ofreduce一起使用。您不能用forEach进行串联执行查询。

const requests = [1, 2];
const resolveWithArg = function(arg) {
  return new Promise(res => setTimeout(() => {
    console.log('resolving with ' + arg);
    res(arg);
  }, 1000))
}
requests.reduce(async(lastPromise, arg) => {
  // the reducer function isn't actually running sequentially itself, it's that they all run immediately, but await the resolve of the previous iteration on the first line
  await lastPromise;
  const result = await resolveWithArg(arg);
  console.log('got result ' + result);
}, Promise.resolve());

最新更新