TransWikia.com

Wait for forEach with a promise inside to finish

Stack Overflow Asked by INbahn on November 27, 2021

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
}

2 Answers

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.

Answered by Abraham Gnanasingh on November 27, 2021

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

Answered by charlietfl on November 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP