@philiprehberger/ts-safe-timeout
v0.1.4
Published
Reliable timeout wrapper for async operations with AbortController support
Readme
@philiprehberger/ts-safe-timeout
Reliable timeout wrapper for async operations with AbortController support.
Installation
npm install @philiprehberger/ts-safe-timeoutUsage
Timeout with Error
import { withTimeout, TimeoutError } from '@philiprehberger/ts-safe-timeout';
try {
const data = await withTimeout(fetch('/api/data'), 5000);
} catch (error) {
if (error instanceof TimeoutError) {
console.log('Request timed out');
}
}Timeout with Fallback
import { withTimeoutFallback } from '@philiprehberger/ts-safe-timeout';
const data = await withTimeoutFallback(fetch('/api/data'), 5000, cachedData);
// Returns cachedData if the fetch takes longer than 5 secondsTimeout Signal
import { createTimeoutSignal } from '@philiprehberger/ts-safe-timeout';
const signal = createTimeoutSignal(5000);
const response = await fetch('/api/data', { signal });With Options
const data = await withTimeout(fetch('/api'), 5000, {
signal: existingAbortSignal, // Also abort on external signal
onTimeout: () => console.warn('Operation timed out'),
});API
| Export | Description |
|--------|-------------|
| withTimeout(promise, ms, options?) | Race promise against timeout, throws TimeoutError on timeout |
| withTimeoutFallback(promise, ms, fallback) | Returns fallback value on timeout instead of throwing |
| createTimeoutSignal(ms) | Creates an AbortSignal that aborts after ms |
| TimeoutError | Error class thrown on timeout, has ms property |
TimeoutOptions
| Option | Type | Description |
|--------|------|-------------|
| signal | AbortSignal | External abort signal |
| onTimeout | () => void | Callback when timeout fires |
Development
npm install
npm run build
npm testLicense
MIT
