Combining Promises

Posted on June 13, 2020https://blog.agney.dev/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

PromiseAn object representing the eventual completion (or failure) of an asynchronous operation, and its resulting value.

You can create a promise with:

const promise = new Promise((resolveCallback, rejectCallback) => {
// Operation
});

You can get result of a promise with:

promise.then((resolvedResult) => {
// This function is called if promise is resolved.
}, (rejectionReason) => {
// This function is called if promise is rejected.
})

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.

A promise can be of three different states:

  1. Pending - meaning that it’s still in flight.
  2. Fulfilled - operation has completed successfully.
  3. 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).

WebMentions

0 Likes
0 Reposts
Buy me a coffeeBuy me a coffee