The type of the function being wrapped
The async function to wrap with timeout functionality
Configuration options
OptionalabortController?: AbortControllerAbort controller to cancel the operation
OptionalonError?: (error: Error, didTimeout: boolean) => voidCapture errors
OptionalonTimeout?: (error: TimeoutError) => voidOn timeout callback
Optionalthrows?: booleanRethrow errors
Timeout in milliseconds after which the function will be rejected
A new async function with the same signature as the original, but with timeout behavior
// Basic usage with a fetch request
const abortController = new AbortController();
const fetchWithTimeout = withTimeout(fetch, { timeout: 5000, abortController });
try {
const response = await fetchWithTimeout('https://api.example.com/data', { signal: abortController.signal });
console.log('Request completed within 5 seconds');
} catch (error) {
if (error instanceof TimeoutError) {
console.log('Request timed out after 5 seconds');
} else {
console.log('Request failed:', error.message);
}
}
// Wrapping a custom async function
async function processData(data: string[]): Promise<string> {
// Simulate slow processing
await new Promise(resolve => setTimeout(resolve, 3000));
return data.join(', ');
}
const abortController = new AbortController();
const processWithTimeout = withTimeout(processData, { timeout: 2000, abortController });
const [result, error] = await attempt(() =>
processWithTimeout(['a', 'b', 'c'], { signal: abortController.signal })
);
if (error) {
console.log('Processing timed out or failed');
} else {
console.log('Result:', result);
}
// Using with database operations
const queryWithTimeout = withTimeout(
async (query: string) => database.execute(query)
{ timeout: 10000 }
);
try {
const users = await queryWithTimeout('SELECT * FROM users');
return users;
} catch (error) {
if (isTimeoutError(error)) {
throw new Error('Database query timed out after 10 seconds');
}
throw error;
}
Wraps an async function with a timeout mechanism. If the function doesn't complete within the specified timeout, it will reject with a TimeoutError.