Promise.race()
Settles as soon as the first input promise settles, fulfilled or rejected.
Syntax
Promise.race(iterable)
Returns
Promise — A promise that adopts the state of the first promise to settle.
Examples
const fast = new Promise(r => setTimeout(() => r("fast"), 10));
const slow = new Promise(r => setTimeout(() => r("slow"), 50));
Promise.race([fast, slow]).then(v => console.log(v));
Output
fast
Promise.race([
Promise.reject(new Error("first")),
Promise.resolve("second"),
]).catch(e => console.log(e.message));
Output
first
Notes
- The first promise to settle wins, whether it fulfills or rejects.
- Commonly used to implement timeouts against a slow operation.
- With an empty iterable the returned promise never settles.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 32 |
| firefox | 29 |
| safari | 8 |
| edge | 12 |
| node | 0.12 |