Promise.race()

rajikaimal

Rajika Imal

Posted on September 28, 2020

Promise.race()

Promise.race() resolves whenever one of the promises resolves. If there are multiple promises, the first promise that gets resolved will be returned.

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => { resolve('one'); }, 500);
});

const promise2 = new Promise((resolve, reject) => {
  resolve('two');
});

Promise.race([promise1, promise2]).then((value) => {
  console.log(value);
  // Both resolve, but promise2 is faster
});
// expected output: "two"
Enter fullscreen mode Exit fullscreen mode

If an empty array is passed, it'll be in forever pending state.

Promise.any() has a similar behavior. But unlike .any(), .race() will return the first fulfilled or rejected promise value. .any() returns fulfilled values only.

💖 💪 🙅 🚩
rajikaimal
Rajika Imal

Posted on September 28, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Promises in JavaScript
javascript Promises in JavaScript

June 17, 2022

Promises in JavaScript
javascript Promises in JavaScript

August 9, 2021

Promise.race()
javascript Promise.race()

September 28, 2020