Deferred Promise Tied to AbortSignal

Expose resolve and reject controls for a promise and automatically reject with AbortError when the linked signal fires.

TypescriptResilience

Code

typescriptsnippet
66 lines
export interface Deferred<Value> {
  readonly promise: Promise<Value>;
  readonly settled: () => boolean;
  resolve(value: Value | PromiseLike<Value>): void;
  reject(reason?: unknown): void;
}

export function createDeferred<Value>(signal?: AbortSignal): Deferred<Value> {
  if (signal !== undefined && !(signal instanceof AbortSignal)) {
    throw new TypeError("signal must be an AbortSignal");
  }
  let settle: ((value: Value | PromiseLike<Value>) => void) | undefined;
  let fail: ((reason?: unknown) => void) | undefined;
  let settled = false;
  const promise = new Promise<Value>((resolve, reject) => {
    settle = resolve;
    fail = reject;
  });
  const markSettled = (): void => {
    settled = true;
  };
  void promise.then(markSettled, markSettled);

  const onAbort = (): void => {
    if (settled || fail === undefined) return;
    settled = true;
    fail(new DOMException("The operation was aborted", "AbortError"));
  };

  if (signal?.aborted === true) {
    onAbort();
  } else if (signal !== undefined) {
    signal.addEventListener("abort", onAbort, { once: true });
    const detach = (): void => signal.removeEventListener("abort", onAbort);
    void promise.then(detach, detach);
  }

  return {
    promise,
    settled: () => settled,
    resolve(value) {
      if (settled || settle === undefined) return;
      settled = true;
      settle(value);
    },
    reject(reason) {
      if (settled || fail === undefined) return;
      settled = true;
      fail(reason);
    },
  };
}

const controller = new AbortController();
const aborted = createDeferred<number>(controller.signal);
aborted.promise.catch((error: unknown) => {
  console.log(error instanceof DOMException ? error.name : "unknown");
});
controller.abort();
console.log(aborted.settled());

const manual = createDeferred<string>();
manual.promise.then((value) => console.log(value));
manual.resolve("done");
manual.resolve("ignored");
console.log(manual.settled());

Output

Captured from a sandboxed run of this snippet in the build pipeline.

true
true
AbortError
done

How it works

Deferred Promise Tied to AbortSignal keeps everything in the functions markSettled, onAbort, detach and createDeferred.

A guard precedes the TypeError: bad state stops the flow there instead of continuing.

What comes back is a new object, not a reference to anything passed in.

What to watch for

  • The guard settled || fail === undefined short-circuits the flow with an early return when its condition holds.

Using it

The surface worth importing is createDeferred; the helpers around it are private to the snippet.

Key statements

let settle: ((value: Value | PromiseLike<Value>) => void) | undefined;
const promise = new Promise<Value>((resolve, reject) => {
  settle = resolve;
  fail = reject;
});
aborted.promise.catch((error: unknown) => {
  console.log(error instanceof DOMException ? error.name : "unknown");
});

Interactive Tools for This Topic

FAQ

Does `createDeferred` modify its input?
No mutation happens — the function reads its input and returns a new value.
How does the snippet fail?
The code refuses to continue: `TypeError` is thrown while the state is still recoverable.
Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `markSettled`, `onAbort`, `detach` at load time.