@padmaj/timeout-promise
v1.0.1
Published
Wrap any promise with a timeout. Throws a clear TimeoutError if it takes too long.
Downloads
331
Maintainers
Readme
@padmaj/timeout-promise
Wrap any promise with a timeout. Throws a clear TimeoutError if it takes too long. Zero dependencies. TypeScript-first.
Install
npm install @padmaj/timeout-promiseUsage
Basic
import { withTimeout } from '@padmaj/timeout-promise'
const data = await withTimeout(fetch('/api/data'), 5000)
// throws TimeoutError if fetch takes longer than 5 secondsCustom error message
const data = await withTimeout(fetch('/api/data'), 5000, {
message: 'API call timed out — try again later'
})Pair with @padmaj/retryable
import { retry } from '@padmaj/retryable'
import { withTimeout } from '@padmaj/timeout-promise'
const data = await retry(
() => withTimeout(fetch('/api/data'), 3000),
{ attempts: 3, delay: 500, backoff: 'exponential' }
)API
withTimeout(promise, ms, options?)
| Param | Type | Description |
|---|---|---|
| promise | Promise<T> | The promise to race against the timeout |
| ms | number | Timeout in milliseconds (must be > 0) |
| options.message | string | Custom error message for TimeoutError |
Returns Promise<T>. Throws TimeoutError if the timeout fires first, or re-throws the original error if the promise rejects.
TimeoutError
Extends Error. Has a ms: number property with the timeout value.
import { withTimeout, TimeoutError } from '@padmaj/timeout-promise'
try {
await withTimeout(fetch('/api'), 3000)
} catch (e) {
if (e instanceof TimeoutError) {
console.error(`Timed out after ${e.ms}ms`)
}
}Notes
- The timer is always cleared when the promise resolves or rejects — no dangling timers.
msmust be a finite number greater than 0 — passing0, negative values,Infinity, orNaNthrows aRangeError.withTimeoutdoes not cancel the underlying promise — it just stops waiting for it. UseAbortControllerif you need true cancellation.
License
MIT
