Skip to content

Function withAbortSignal

Source: WithAbortSignal.ts

Wraps an async task with an AbortSignal. If the signal fires before the task settles, the returned promise rejects with an AbortedError (a DOMException with name 'AbortError').

The underlying task continues running after the signal fires. To truly cancel it, the task itself must observe the signal.

Import

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

Signature

ts
function withAbortSignal<T>(
    signal: AbortSignal,
    asyncTask: Promise<T> | (() => Promise<T>),
    opts?: IWithAbortSignalOptions<T>,
): Promise<T>;

Parameters

  • Parameter signal: AbortSignal

    The abort signal to observe. If already aborted when called, rejects immediately.

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

    The task to run. When the task is a factory function, it is called immediately. If signal is already aborted and asyncTask is a factory function, it is not called.

  • Parameter opts?: IWithAbortSignalOptions<T>

    Optional. See IWithAbortSignalOptions.

Return Value

The resolved value of asyncTask if it completes before the signal fires.

Error Handling

  • AbortedError — Rejected if the signal fires. .unresolvedPromise holds the still-running task, or null if the signal was already aborted before the task started.

Examples

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

const ac = new AbortController();
setTimeout(() => ac.abort(), 1000);

try {
    const result = await withAbortSignal(ac.signal, () => longRunningTask());
} catch (e) {
    if (e instanceof DOMException && e.name === 'AbortError') {
        console.log('Task was aborted');
    }
}