Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for forEach with a promise inside to finish

Tags:

javascript

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
}
like image 968
INbahn Avatar asked Jul 13 '17 13:07

INbahn


People also ask

Does Javascript wait for forEach to finish?

prototype. forEach method accepts a callback as an argument which can be an asynchronous function, but the forEach method will not wait for any promises to be resolved before moving onto the next iteration.

How do you wait for loop to finish?

To use Javascript promises in a for loop, use async / await . This waits for each promiseAction to complete before continuing to the next iteration in the loop.

Is promise all parallel?

Often Promise. all() is thought of as running in parallel, but this isn't the case. Parallel means that you do many things at the same time on multiple threads. However, Javascript is single threaded with one call stack and one memory heap.


2 Answers

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
})
like image 145
charlietfl Avatar answered Sep 17 '22 12:09

charlietfl


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.

like image 25
Abraham Gnanasingh Avatar answered Sep 21 '22 12:09

Abraham Gnanasingh