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
import { withAbortSignal } from '@litert/utils-async';Signature
function withAbortSignal<T>(
signal: AbortSignal,
asyncTask: Promise<T> | (() => Promise<T>),
opts?: IWithAbortSignalOptions<T>,
): Promise<T>;Parameters
Parameter
signal: AbortSignalThe 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
signalis already aborted andasyncTaskis 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..unresolvedPromiseholds the still-running task, ornullif the signal was already aborted before the task started.
Examples
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');
}
}