【问题标题】:Using a foreach traversal to invoke an asynchronous function, returns the result and the request is not normal? [duplicate]使用foreach遍历调用异步函数,返回结果请求不正常? [复制]
【发布时间】:2018-04-27 02:09:55
【问题描述】:

<!-- 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 我怎样才能得到想要的结果? 请求参数与返回结果的一致性如何?

【问题讨论】:

  • 您缺少一个分号(或几个分号),这将导致意外行为或错误。
  • IIFE 的目的是什么。似乎非常不必要。 let _self = this 很奇怪。

标签: javascript asynchronous foreach


【解决方案1】:

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

【讨论】:

  • 当答案对您有用时,请投票并接受它们以向其他用户表明它解决了您的问题:)
  • 好的,我已经投票了;不知道你是不是这个意思?这是我关于stackoverflow的第一个问题,
猜你喜欢
  • 1970-01-01
  • 2022-12-22
  • 1970-01-01
  • 2019-09-30
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多