Promise.race takes an array of promises and returns one promise that settles with the first input to settle, whether fulfilled or rejected. section 8.1.3
Listing 8.5 Using Promise.race to enforce a timeout
const fetchController = new AbortController(); #A
const fetchPromise = fetch("https://httpbin.org/delay/2", { #B
signal: fetchController.signal, #B
}).then((response) => { #B
if (!response.ok) { #B
throw new Error(`Status code ${response.status}`); #B
} #B
return response.json(); #B
});
const timeoutPromise = new Promise((_, reject) => #C
setTimeout(() => { #C
fetchController.abort(); #C
reject(new Error("Request timeout"));
}, 1_000), #C
); #C
Promise.race([fetchPromise, timeoutPromise]) #D
.then((result) => {
console.log(result);
})
.catch((reason) => {
console.error(`Request failed: ${reason}`);
});
A timeout promise can race a fetch. The example uses AbortController to abort the fetch when the timer fires; racing alone would not stop the losing request. section 8.1.3

