JavaScript Snippet

Timeout a Promise

Difficulty: Easy

A promise that never settles will leak handles and stall UI flows; wrapping it with a deadline turns a bug into a recoverable error. This snippet shows the classic `Promise.race` pattern, then upgrades it to clean up the timer on success and to forward an `AbortSignal` so cancelled work stops doing real I/O. Use it around any `fetch`, DB call, or third-party SDK that does not expose a native timeout option.

Code Snippets
/

Timeout a Promise

Timeout a Promise

A promise that never settles will leak handles and stall UI flows; wrapping it with a deadline turns a bug into a recoverable error. This snippet shows the classic `Promise.race` pattern, then upgrades it to clean up the timer on success and to forward an `AbortSignal` so cancelled work stops doing real I/O. Use it around any `fetch`, DB call, or third-party SDK that does not expose a native timeout option.

JavaScript
Easy
3 snippets
async-programming
promises
utility
error-handling

737 views

15

Promise.race settles with whichever input promise settles first, so racing the real work against a setTimeout rejection gives you a deadline. The rejection message becomes the error your callers see, so make it descriptive (which call timed out, and how long was the budget). The downside of this minimal version is that the timer keeps running even after the underlying promise resolves, briefly delaying process exit in scripts and leaking timers in long-lived servers. Reach for the cleanup variant in production code.