how to do async await on a forEach function

24,502

Solution 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.

Solution 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;
});
Share:
24,502
anoop chandran
Author by

anoop chandran

Updated on May 15, 2020

Comments

  • anoop chandran
    anoop chandran almost 4 years

    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?

  • Roy Wang
    Roy Wang almost 6 years
    yes, makeRequest should return a promise.
  • anoop chandran
    anoop chandran almost 6 years
    super it worked!