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
- 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 throughPromise.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
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
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
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:
The snippet above will never get settled (fulfilled or rejected) because the static method’s argument is an empty array.