What is Promise.race in JavaScript?

Promise.race takes a list of promises as an argument and returns a promise as soon as one of the promises from the list is resolved or rejected.

Console

In the above code, we sent 2 promises to the Promise.race method. The first method will execute after 100ms, and the second method will execute after 50ms. In this case, as soon as the second promise is resolved, Promise.race will return the second promise.


Let’s consider that we have two promises, and one will be rejected and one will be resolved. Consider that the promise which rejects will be done first. In this case, the rejected promise will be returned from Promise.race.

Console

If we send an already resolved promise in the list of promises, then the first values will be returned.

Console

If we pass a value to the promise list, then that will be returned.

Console

Promise.any vs. Promise.race

Promise.any will return the first fulfilled promise, whereas Promise.race will return the first settledfirst resolved or ejected promise.

Console

In the above code, when we call Promise.any, although promise2 rejects first, promise1 will be returned because Promise.any will return the first fulfilled promise. When we call Promise.race, promise2 will be returned because Promise.race will return the first settled promise.

Free Resources