JavaScript Reference ยท Promises and Async
Promise.race()
Reference for Promise.race(): settle with the first promise to fulfill or reject, build timeouts, and avoid the empty-iterable trap that never settles.
Promise.race() returns a promise that settles as soon as any input promise settles, copying that input's outcome. If the quickest input fulfills, the result fulfills with its value; if the quickest one rejects, the result rejects with its reason.
The classic use is a timeout: race the real work against a timer that rejects. It is also handy for "whichever answers first" situations when failures should count as answers too.
const result = await Promise.race([loadData(), timeout(3000)]);
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Promise.race(iterable)
| Name | Description |
|---|---|
iterable |
An iterable of promises or plain values. |
Return value: a promise that fulfills or rejects like the first input to settle. With an empty iterable it stays pending forever.
Exceptions: if the argument is not iterable, the returned promise rejects with a TypeError.
Usage notes
- First settlement, good or bad. A fast failure beats a slower success. For "first success", use
Promise.any(). - Losers are not cancelled. The other tasks keep running; only their results are ignored. Cancel real work with an
AbortController. - Clear the timer. In a timeout helper, call
clearTimeout()so the timer does not keep the program alive or fire later. - Empty input never settles. Guard against empty arrays if the list is dynamic.
- Plain values count as settled, so earlier plain values win over later promises.
- Ties are decided by input order, because handlers are attached in that order.
- Timeout rejections should use a clear
Errormessage so callers can tell them from real failures.
Browser support
Supported in every current browser and Node.js.