Skip to content

Promise.race() – What Is the JavaScript Promise race() Method?

Promise.race() is a static method of the Promise constructor function. It returns a new promise object after JavaScript fulfills or rejects any item in the iterable value you’ve provided as its argument.

Syntax of the Promise.race() Static Method

Promise.race(iterable);
  • The race() method’s iterable argument’s items can be promises, thenables, or any of JavaScript’s data types.
  • Promise.race() will automatically pass each of its iterable argument’s items through Promise.resolve(). Therefore, race() will eventually resolve all its iterable argument’s items to a fully-fledged promise object.

Example of Promise.race() Returning a Fulfilled Promise

Promise.race(["Orange", Promise.resolve(24), 715]);
// The invocation above will return:
Promise { <state>: "fulfilled", <value>: "Orange"}

The snippet above returned a fulfilled promise immediately after JavaScript resolved an item in the array argument.

Example of Promise.race() Returning a Rejected Promise

const item1 = Promise.reject(24);
const item2 = Promise.reject(715);
const item3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Orange");
}, 30000);
});
const item4 = "Pinkmelon";
Promise.race([item1, item2, item3, item4]).then((value) => {
console.log(value);
});
// The invocation above will return:
// Promise { <state>: "rejected", <reason>: 24 }
// Uncaught (in promise) 24

The snippet above returned a rejected promise immediately after JavaScript resolved an item in the array argument.

Example of Promise.race() Returning the First Resolved Promise’s Value

{
const item1 = new Promise((resolve, reject) => {
setTimeout(resolve, 8000, "Orange");
});
const item2 = new Promise((resolve, reject) => {
setTimeout(reject, 3000, "Banana");
});
const item3 = new Promise((resolve, reject) => {
setTimeout(resolve, 50000, "Grape");
});
Promise.race([item1, item2, item3]).then((value) => {
console.log(value);
});
}
// The invocation above will first return:
// Promise { <state>: "pending" }
// Then, after 3000 milliseconds (3 seconds), the invocation will return:
// "Uncaught (in promise) Banana"

The snippet above returned the value of the promise JavaScript first settled.

What Happens If Promise.race()’s Argument Is an Empty Array?

Suppose race()’s argument is an empty array. In that case, its promise will remain pending—forever.

Here’s an example:

Promise.race([]);
// The invocation above will return:
Promise { <state>: "pending" }

The snippet above will never get settled (fulfilled or rejected) because the static method’s argument is an empty array.