Combining Promises
Prerequisites
It is quite common during web development that we run across scenarios where we have to orchestrate different asynchronous operations together. This blog describes ways in which we can combine Promises, our default async operation strategy and their applications.
Terminology
You can create a promise with: You can get result of a promise with: A Promise is also a guarantee of an asychronous operation, any operation that is wrapped in a Promise will only be resolved or rejected only by the next clock tick.Promise
An object representing the eventual completion (or failure) of an asynchronous operation, and its resulting value.
A promise can be of three different states:
- Pending - meaning that it’s still in flight.
- Fulfilled - operation has completed successfully.
- Rejected - operation has failed.
A promise that is either Fulfilled or Rejected is said to be settled.
Combinators
All of the combinators take an array of Promises as argument.
Promise.all
This is the most widely used among the combinators. Here is how we can use it:
Promise.all([promiseA, promiseB]).then(([promiseAResponse, promiseBResponse]) => {// Do something with it here});
Promise.all
is fulfilled if all promises that are provided to it are fulfilled or if one of the promises is rejected.
Promise.race
Promise.race([promiseA, promiseB]).then(([promiseAResponse, promiseBResponse]) => {// Do something with it here});
Promise.race
is fulfilled when one of the promises is settled (fulfilled or rejected).
Promise.allSettled
Promise.allSettled([promiseA, promiseB]).then(([promiseAResponse, promiseBResponse]) => {// Do something with it here});
Returns when all promises are settled (fulfilled or rejected).