Wait for forEach with a promise inside to finish
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.
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
})