Skip to content

Function withTimeout

Source: WithTimeout.ts

Wraps an async task with a deadline. If the task does not settle within timeoutMs milliseconds, the returned promise rejects with a TimeoutError.

The underlying task continues running after a timeout. If you need true cancellation, use AbortTimeoutController and pass the signal into the task.

Import

ts
import { withTimeout } from '@litert/utils-async';

Signature

ts
async function withTimeout<T>(
    timeoutMs: number,
    asyncTask: Promise<T> | (() => Promise<T>),
    opts?: IWithTimeoutOptions<T>,
): Promise<T>;

Parameters

  • Parameter timeoutMs: number

    Maximum wait time in milliseconds.

  • Parameter asyncTask: Promise<T> | (() => Promise<T>)

    The task to run. Can be an already-started Promise, or a factory function that returns one (called immediately).

  • Parameter opts?: IWithTimeoutOptions<T>

    Optional. See IWithTimeoutOptions.

Return Value

The resolved value of asyncTask if it completes before the timeout.

Error Handling

  • TimeoutError — Rejected if the task exceeds timeoutMs. The .unresolvedPromise property holds a reference to the still-pending task.
  • Any error thrown by asyncTask — Re-thrown if the task fails before the timeout.

Examples

ts
import { withTimeout, TimeoutError } from '@litert/utils-async';

// With a factory function
try {
    const result = await withTimeout(5000, () => fetch('https://api.example.com/data'));
    console.log(result);
} catch (e) {
    if (e instanceof TimeoutError) {
        console.error('Request timed out');
    }
}

// Collect the late result
const result = await withTimeout(1000, longTask(), {
    collectResult: (err, val) => {
        if (!err) console.log('Late result:', val);
    },
}).catch(() => null);