11

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
  • 630,263
  • 148
  • 957
  • 1,375
anoop chandran
  • 1,460
  • 5
  • 23
  • 42
  • Where the rest of the code? You need the outer promise too to refactor this correctly – Liam May 14 '18 at 10:33
  • Async await + Array.prototype.map(): `.then(async () => ['url1', 'url2', 'url3', 'url4'].map(async url => await makeRequest(url)));` – Yosvel Quintero May 14 '18 at 11:11

2 Answers2

16

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
  • 11,112
  • 2
  • 21
  • 42
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
  • 13,291
  • 2
  • 19
  • 37