10

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?

Bergi
  • 572,313
  • 128
  • 898
  • 1,281
anoop chandran
  • 1,370
  • 4
  • 21
  • 38

2 Answers2

14

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.

Roy Wang
  • 10,796
  • 2
  • 16
  • 37
8

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;
});
Faly
  • 12,802
  • 1
  • 18
  • 35