Promises with loops in Node JS
Running all actions asynchronously by default is one of nodes greatest strengths. Waiting for an action to finish is very easy with promises. But how do you wait for multiple promises which might take different amount of time to finish? For example when you're looping through a list and run an asynchron function in each loop iteration.
There is a simple little helper function within Promise
called all()
. This function takes a array of promises and resolves as soon as all promises in the list are resolved or an error occures in one of them.
Here is an example:
let promises = [];
for (const item of list) {
// Add new promise
promises.push(
self.actionWhichReturnsAPromise(item)
);
}
Promise.all(promises)
.then(() => {
console.log('All actions run without any issues!');
}).catch((error) => {
console.log('An error occured!');
console.error(error);
});