how to do async await on a forEach function [duplicate]

天涯浪子 提交于 2020-01-15 03:39:40

问题


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
})

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?


回答1:


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.




回答2:


You cannot wait for all the promises to be resolved if you use forEach. Use for .. of instead:

}).then(async function() {
    var arr = ['url1', 'url2', 'url3', 'url4'];
    var responseArray = []; 
    for (url of arr) {
        cont response = await makeRequest(url);
        responseArray.push(response);
    }
    return responseArray;
});

Or, for a better performance, you can use Promise.all to launch all your requests in parallel:

}).then(async function() {
    var arr = ['url1', 'url2', 'url3', 'url4'];
    var responseArray = await Promise.all(arr.map(function(url) {
        return makeRequest(url);
    }));
    return responseArray;
});


来源:https://stackoverflow.com/questions/50328143/how-to-do-async-await-on-a-foreach-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!