Promise in Node.js/JavaScript–Part IV

Posted: October 15, 2021 in Javascript, Node.js
Tags: , ,

In the last post, we have seen how we can sequentially execute promises using Promise chaining via the Promise.resolve and Array.prototype.reduce functions. In this post, we will see how we can execute the promises in parallel using the Promise.all function.

As per documentation the Promise.all does the following:

The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will resolve when all of the input’s promises have resolved, or if the input iterable contains no promises. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.

We will use the similar tasks as we had used in the previous post but here we will go for parallel execution instead of sequential.

image

image

image

Note that Task3 has minimum timeout period and Task2 has maximum.

Now we will create an array (iterable) of promises by executing these three tasks with an input value.

image

We will invoke the Promise.all method using this promises array.

image

The output will be as follows:

image

The timings clearly shows that:

  • Tasks are started and executed almost in parallel
  • Task3 is completed early , followed by Task1 and then Task2 based on their timeout interval of the setTimeout function.
  • The returned promise i.e. aggrPromise is resolved when all input promises are resolved and the results are printed as per their order in the input array.

image

The returned promise rejects immediately if any of the input promises is rejected. We will examine this by passing a negative value to the third function as shown below:

image

The output will be as follows:

image

We can see that both Task1 and Task2 are completed but the resultant promise rejects immediately with the error message.

image

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.