The Promise.race()
method in JavaScript takes an array (or iterable) of promises and returns a single promise that resolves or rejects as soon as the first promise in the iterable settles (either resolves or rejects).
Promise.race()
is useful when you want to wait for the first settled promise (whether it's a success or a failure).
iterable
: An array or iterable of promises.
Output:
✅ promise2
resolves first after 500ms, so the result is 'Promise 2 resolved'
.
Promise.race
Output:
✅ The timeout
promise rejects after 2 seconds, so the race is settled with the rejection message 'Request timed out'
.
✔️ Fastest response wins scenario
✔️ Implementing a timeout for network requests
✔️ Resolving the quickest result among multiple sources
Promise.race()
returns the result of the first settled promise.Promise.race()
will reject.