16

I have a problem with waiting for my forEach loop, which has a promise inside, to finish. I can't find any real solution, that would make the script wait till the end, before continuing with the execution. I cannot make the someFunction synchronous.

makeTree: function (arr) {
    arr.forEach(function (resource) {
        someModule.someFunction(resource).then(function () { //a Promise
            //do something with the resource that has been modified with someFunction
        });
    });
    // do something after the loop finishes
}
INbahn
  • 183
  • 1
  • 2
  • 7

2 Answers2

35

Instead of forEach() use map() to create an array of promises and then use Promise.all()

let promiseArr = arr.map(function (resource) {
    // return the promise to array
    return someModule.someFunction(resource).then(function (res) { //a Promise
        //do something with the resource that has been modified with someFunction
        return res;
    })
});

Promise.all(promiseArr).then(function(resultsArray){
   // do something after the loop finishes
}).catch(function(err){
   // do something when any of the promises in array are rejected
})
ctf0
  • 6,991
  • 5
  • 37
  • 46
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • 1
    Thanks so much for your answer, I had the same doubt and I didn't want to do with packages or something complex. this is the best response for these cases, very simple and brilliant. again, thanks. regards – makitocode Jun 08 '18 at 00:45
  • Simple and clear to read + maintain: thank you for this solution! – Cécile Fecherolle Sep 27 '18 at 13:46
  • not working for me if I don't have anything return from my function – Ray Feb 02 '20 at 05:10
3

Try this,

makeTree: function (arr) {
   var promises = [];
   arr.forEach(function(resource) {
      promises.push(someModule.someFunction(resource));
   });
   Promise.all(promises).then(function(responses) {
      // responses will come as array of them
      // do something after everything finishes
   }).catch(function(reason) {
      // catch all the errors
      console.log(reason);
   });
}

You can refer this link for more on Promise.all with simple examples.

Abraham Gnanasingh
  • 837
  • 2
  • 10
  • 31