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 singlePromise
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.
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.
We will invoke the Promise.all method using this promises array.
The output will be as follows:
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.
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:
The output will be as follows:
We can see that both Task1 and Task2 are completed but the resultant promise rejects immediately with the error message.