Skip to content

timeout

Wraps a promise to reject with a TimeoutError if it does not resolve within the specified duration.

Available since v2.0.0

import { timeout } from '@helpers4/promise';
// or, from the all-in-one package (same code, one install):
import { timeout } from 'helpers4/promise';
timeout<T>(promise: Promise<T>, ms: number): Promise<T>
ParameterTypeDescription
promisePromise<T>The promise to wrap
msnumberTimeout duration in milliseconds

Promise<T> — A promise that rejects with TimeoutError if the timeout is exceeded

Throws a TimeoutError if the promise does not resolve in time.

await timeout(fetch('/api/data'), 5000)
// Rejects with TimeoutError if fetch takes longer than 5s

Returns the value if the promise resolves before the timeout.

const result = await timeout(Promise.resolve('fast'), 1000)
// => 'fast'

View source on GitHub