javascript / intermediate
Snippet
Race Conditions and Timeouts with Promise.race()
Promise.race() returns a promise that settles as soon as any of the input promises settles (either resolves or rejects). This is commonly used to implement timeouts for network requests or long-running operations.
snippet.js
1
2
3
4
5
6
const fetchData = new Promise(resolve => setTimeout(() => resolve('Data'), 5000));const timeout = new Promise((_, reject) => setTimeout(() => reject('Request timed out'), 2000));Promise.race([fetchData, timeout]).then(console.log).catch(console.error);
Breakdown
1
Promise.race([fetchData, timeout])
Waits for the very first promise in the array to finish.
2
reject('Request timed out')
If the timeout settles first, the whole race is rejected.
3
.catch(console.error);
Handles the rejection if the timeout triggers before the data arrives.