Junior
Tell me about what Promise.race is.
sobes.tech AI
Answer from AI
Promise.race is a method that returns a new promise. This new promise resolves or rejects with the same value (or reason) as the first promise from the provided iterable object (usually an array) that settles.
Working principles:
- Input: Accepts an iterable object (e.g., an array) of promises.
- Waiting: Starts a "competition" among all promises.
- Result: As soon as any of the promises in the iterable object settles (either resolves or rejects),
Promise.raceimmediately settles with the same result. - Ignoring: Results of all other promises that settle later are completely ignored.
Example usage:
// Example of a promise that resolves after 1 second
const promise1 = new Promise((resolve) => setTimeout(() => resolve('First'), 1000));
// Example of a promise that resolves after 500 milliseconds
const promise2 = new Promise((resolve) => setTimeout(() => resolve('Second'), 500));
// Example of a promise that rejects after 300 milliseconds
const promise3 = new Promise((_, reject) => setTimeout(() => reject(new Error('Error')), 300));
Promise.race([promise1, promise2, promise3])
.then((value) => {
console.log(value); // Will output 'Error'
})
.catch((error) => {
console.error(error.message); // Handles the error 'Error'
});
In this example, promise3 settles first (rejects), so Promise.race will settle with an error, and the .catch block will execute. If promise2 had settled first (for example, in 10ms), then Promise.race would resolve with the value 'Second', and the .then block would execute.
Typical use cases:
- Implementing a timeout for an asynchronous operation.
- Getting the result from the fastest data source among several options.
- Cancelling competing asynchronous operations.