Skip to content

abortableRace<const T>

An abort-scoped Promise.race.

Calls executor with a child abort signal, which aborts when abortSignal aborts or when the first task settles. The returned promise settles only once every task has settled, so no task outlives the group, and it settles like the first task that settled. One exception keeps a real failure from being swallowed: a later rejection that is not an AbortError wins over a first task that fulfilled or rejected with an AbortError.

The tasks must honour the child signal, rejecting once it aborts, either at once or after their cleanup. A task that ignores it keeps the group waiting for it.

With no tasks, the returned promise settles only when abortSignal aborts, rejecting with its reason, as Promise.race([]) never settles.

Import:

import { abortableRace } from '@mnaoumov/typescript-lib/abortable-tasks';

Example:

const result = await abortableRace(abortSignal, (childAbortSignal) => [
sleep(5000, childAbortSignal).then(() => ({ status: 'timeout' as const })),
fetchUser(childAbortSignal).then((user) => ({ status: 'success' as const, user }))
]);

Signature:

function abortableRace(abortSignal: AbortSignal, executor: AbortableTasksExecutor<T>): Promise<Awaited<T[number]>>

Parameters:

Parameter Type Description
abortSignal AbortSignal Aborts the whole group. If it is already aborted, executor is never called.
executor AbortableTasksExecutor<T> Builds the tasks from the child abort signal.

Returns: Promise<Awaited<T[number]>> — A Promise that settles like the winning task, or rejects with the reason of abortSignal if it was already aborted.

Example:

const result = await abortableRace(abortSignal, (childAbortSignal) => [
sleep(5000, childAbortSignal).then(() => ({ status: 'timeout' as const })),
fetchUser(childAbortSignal).then((user) => ({ status: 'success' as const, user }))
]);