fbpx

Collect results from multiple promises in NodeJS

Promises can be complicated by themselves and may take time for a programmer who is otherwise comfortable with a procedural style of programming.

In certain cases, you maybe required to not just executed one promise, but execute multiple promises and collectively process the results from each of the promises. This article provides an example of the same.

let promises = [];
  
let numbers = [1,2,3,4,5];
numbers.forEach(number => {
let promise = new Promise(function(resolve, reject){
    resolve (number * number);
  });
  promises.push(promise);
})

Promise.all(promises).then(squares => console.log(JSON.stringify(squares)));

The above program performs a square of each of the numbers in an array, but each square operation is executed asynchronously. The return of the asynchronous operation is got using a promise.

Each promise is created within an array and added to a promises array.

Promise.all() function is called that invokes and awaits execution of all the promises. Once every promise is resolved (or rejected), the result of each promise is collected into an array, in our case this is the “squares” variable.

The output of the above program looks as shown below

[1,4,9,16,25]

You can notice that the output is in the same order as the input numbers. Rather it is in the same order as the “promises” array. The Promise.all() function ensures that ordering of responses is maintained.

Let us take another example.

let promises = [];
  
let numbers = [-1,0,1,2,3,4,5];
numbers.forEach(number => {
let promise = new Promise(function(resolve, reject){
    if(number < 0) reject('Only positive numbers accepted');
    else resolve (number * number);
  }).catch(err => console.log(err));
  promises.push(promise);
})

Promise.all(promises).then(squares => console.log(JSON.stringify(squares)));

The above program rejects the scenario for squaring a negative number. Let’s see what the output looks like in this case.

Only positive numbers accepted
[null,0,1,4,9,16,25]

The first log line comes from the “catch” condition in the promise itself. The second line shows output after Promise.all(). We can see that we have a “null” value for square of -1, as the promise rejected a negative number.

The ordering of responses in the array is still maintained even if any of the promise is rejected. The array will contain a “null” value for promises that either reject or ones that resolve with a “null” value.

learn-ai-and-ml
%d bloggers like this: