首页 > 解决方案 > 使用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 我怎样才能得到想要的结果?请求参数如何与返回结果一致?

标签: javascriptasynchronousforeach

解决方案


听起来您想串行执行查询,而不是并行执行。所以,每次迭代的开始都应该等到前一次迭代的分辨率才开始。awaitfor..of或一起使用reduce。您不能与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());


推荐阅读