TASIOMIND.DEV — OPERATIONAL▸▸▸FULL STACK DEVELOPER @ GWQ SERVICEPLUS AG▸▸▸FOUNDER — K8SGPT.AI▸▸▸OPEN SOURCE: ACTIVE▸▸▸DISTRIBUTED SYSTEMS / KUBERNETES / AI▸▸▸RUST + GO + PYTHON▸▸▸FIELD TESTED / STATUS — NOMINAL▸▸▸LOCATION: EUROPE/BERLIN▸▸▸TASIOMIND.DEV — OPERATIONAL▸▸▸FULL STACK DEVELOPER @ GWQ SERVICEPLUS AG▸▸▸FOUNDER — K8SGPT.AI▸▸▸OPEN SOURCE: ACTIVE▸▸▸DISTRIBUTED SYSTEMS / KUBERNETES / AI▸▸▸RUST + GO + PYTHON▸▸▸FIELD TESTED / STATUS — NOMINAL▸▸▸LOCATION: EUROPE/BERLIN▸▸▸

Combining Promises

June 13, 2020

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

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

You can create a promise with:

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

You can get result of a promise with:

code
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:

code
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

code
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

code
Promise.allSettled([promiseA, promiseB]).then(
  ([promiseAResponse, promiseBResponse]) => {
    // Do something with it here
  },
);

Returns when all promises are settled (fulfilled or rejected).