Timeout Pattern with Promise.race
You'll learn how to build a timeout mechanism that automatically rejects a promise if it takes too long to resolve.
The Core Idea
Sometimes a promise might take longer than acceptable—maybe a network request hangs, or a database query stalls. By racing your actual promise against a "timeout promise" that rejects after a certain delay, you can ensure your code doesn't wait forever.
The timeout promise is simply a promise that rejects after a specified duration using setTimeout. When you pass both promises to Promise.race(), whichever settles first wins—either your operation completes in time, or the timeout fires.
How It Works
Create a helper function that returns a promise which rejects after a delay:
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error(`Operation timed out after ${ms}ms`));
}, ms);
});
}
Now race this against your actual operation:
const fetchData = fetch('https://api.example.com/data');
Promise.race([
fetchData,
timeout(5000)
])
.then(result => {
console.log('Success:', result);
})
.catch(error => {
console.log('Failed or timed out:', error.message);
});
If fetchData resolves within 5 seconds, you get the result. If not, the timeout promise rejects first, and your .catch() handles the timeout error.
Why This Matters
Without timeouts, slow operations can hang indefinitely, freezing UI or blocking resources. This pattern gives you control over maximum wait times, improving user experience and application reliability.
Key Takeaway: Race your promise against a timeout promise to automatically fail slow operations, preventing indefinite hangs and giving users faster feedback.