如何在forEach函数上进行异步等待 [英] how to do async await on a forEach function

查看:234
本文介绍了如何在forEach函数上进行异步等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是异步等待和承诺的初学者.我看了几篇文章,也看了几篇教程视频,但是我仍然无法完全理解它. 所以我有一个正在使用的代码

I'm a beginner in async await and promises. I read few articles and watch few tutorial videos but I am still not able to understand it completely. So I have a code that I'm working on right now

}).then(function() {
  var responseArray = []
  [url1,url2,url3,url4].forEach((url)=>{
      makeRequest(url)
  }).then((response)=>{
      responseArray.push(response)
  })
  return responseArray
})

因此,正如预期的那样,responseArray返回为空.我需要等到每个makerequest(url)的所有响应都推送到responseArray上.
这是我的尝试

So as expected the responseArray is returned empty. I need to make it wait until all the responses from each makerequest(url) is pushed to the responseArray.
This is my attempt

}).then(function() {
      var responseArray = []
      [url1,url2,url3,url4].forEach((url)=>{
          async makeRequest(url)
      }).then((response)=>{
          await responseArray.push(response)
      })
      return responseArray
    })

有人可以帮我解决这个问题吗?

Can anyone help me fix this one?

推荐答案

您需要将请求映射到一个Promise数组,然后使用

You need to map the requests to an array of promises then use Promise.all:

.then(async () => {
  const responseArray = await Promise.all(
    [url1, url2, url3, url4].map(makeRequest)
  );
})

这将并行执行所有请求(除非您希望限制带宽等,否则通常就是您想要的).

This will execute all the requests in parallel (which is generally what you want unless you want to limit the bandwidth etc).

如果您要按顺序执行它们,则有有关最佳方法的大量讨论

If you want to execute them sequentially, there's a huge discussion on the best approach.

这篇关于如何在forEach函数上进行异步等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆