Search This Blog

2021/01/10

Promise.all in Node.js

Promise.all() static method used to aggregate results from multiple asynchronous operations.

The Promise.all() static method accepts a list of Promises and returns a Promise that:

  • resolves when every input Promise has resolved or

  • rejected when any of the input Promise has rejected.

Example 1:

const p1 = new Promise((resolve, reject) => {

setTimeout(() => {

console.log('The first promise has resolved');


resolve(10);

}, 1 * 1000);


});


const p2 = new Promise((resolve, reject) => {

setTimeout(() => {

console.log('The second promise has resolved');

resolve(20);

}, 2 * 1000);

});


const p3 = new Promise((resolve, reject) => {

setTimeout(() => {

console.log('The third promise has resolved');

resolve(30);

}, 3 * 1000);

});


Promise.all([p1, p2, p3])

.then(results => {

const total = results.reduce((p, c) => {return p + c},0);



console.log(`Results: ${results}`);

console.log(`Total: ${total}`);

});



Output:

The first promise has resolved

The second promise has resolved

The third promise has resolved

Results: 10,20,30

Total: 60


Here all promises resolves.Result of promise.all is an array containing result of each members result .e.g. [10,20,30]


Example 2:

const p1 = new Promise((resolve, reject) => {

setTimeout(() => {

console.log('The first promise has resolved');

resolve(10);

}, 1 * 1000);


});


const p2 = new Promise((resolve, reject) => {

setTimeout(() => {

console.log('The second promise has rejected');

reject('Failed');

}, 2 * 1000);

});


const p3 = new Promise((resolve, reject) => {

setTimeout(() => {

console.log('The third promise has resolved');

resolve(30);

}, 3 * 1000);

});


Promise.all([p1,p2, p3])

.then(function(results){

console.log(`Results: ${results}`);

}) // never execute

.catch(function(err){

console.log("err:",err);

});

Output:

The first promise has resolved

The second promise has rejected

err: Failed

The third promise has resolved




Here one promise get rejected so promise.all get rejected too.

No comments:

Post a Comment