Promise.all is iterable promise object which is a powerful promise API and allows us to perform asynchronous operations. Promise.all takes multiple promises as an array. Promise.all maintains the order in which promises are added into an promise array. Lets see it through an example.
function sendNotification(userid){
return new Promise((resolve, reject) => {
if(userid > 100){
resolve('User has been notified - ' + userid);
}else{
reject('userid provided in invalid')
}
});
}
const userid = [ 10,50,70,40,100, 102,78 ];
const promises = []; //initialize the promise array
userid.forEach(id=> promises.push(sendNotification(userid)));
Promise.all(promises).then(resp => console.log(resp))
.catch(err => console.log(err))
in example above, we can see that promises are executed one by one by using Promise.all. The problem with this code is that if one promise gets rejected, it will reject all the other promises. If we do not want that then you need to handle the errors for each promise before we create an promise array. In example below, we can see that the rejects are handled inside each promise and when called promise.all, it will resole and give us an array for each promise response.
function sendNotification(userid){
return new Promise((resolve, reject) => {
if(userid > 100){
resolve('User has been notified - ' + userid);
}else{
reject('userid provided in invalid')
}
});
}
const userid = [ 10,50,70,40,100, 102,78 ];
const promises = []; //initialize the promise array
userid.forEach(id=> promises.push(sendNotification(id).catch(err=>console.log(err)))); // catching each promise's error here
Promise.all(promises).then(resp => console.log(resp));
.catch(err => console.log(err));
Why should you use promise.all
- Let’s assume we have to send notification to 1million users. It can make your stack heavy and can kill your server. But promises.all helps you overcome this issue.
- When code needs to run multiple asynchronous functions or promises simultaneously.
I hope this post was helpful to you. If you like my post, follow me @twitter/andramazo.