Working with Multiple Promises: Racing Promises

Learn how JavaScript handles multiple promises by racing promises.

In the examples so far, promises were used to implement a single asynchronous task. In nontrivial scenarios, we may need multiple asynchronous tasks to be executed to solve a problem.

An analogy

A currency exchange broker may want to pick the best price quote from more than one provider. A promise carries the response for a single asynchronous task, but when dealing with multiple tasks, we need to combine data from multiple asynchronous functions, each returning a promise.

Handling multiple asynchronous functions

JavaScript provides two options for dealing with multiple asynchronous tasks:

  • Let the tasks race and pick the first promise that resolves or rejects
  • Wait for all the tasks to resolve or for any one of them to reject

Let’s explore each of these options with examples.

Racing promises

The race() static method of Promise takes an array of promises and returns the first one to resolve or reject.

Let’s create two promises: one that resolves after a delay and the other that rejects after a timeout has expired.

Get hands-on with 1200+ tech skills courses.