Function abortable

  • Make a Promise abortable with the given signal.

    Type Parameters

    • T

      The type of the provided and returned promise.

    Parameters

    • p: Promise<T>

      The promise to make abortable.

    • signal: AbortSignal

      The signal to abort the promise with.

    Returns Promise<T>

    A promise that can be aborted.

    If the signal is already aborted and signal.reason is undefined. Otherwise, throws signal.reason.

    import { abortable, delay } from "@std/async";
    import { assertRejects, assertEquals } from "@std/assert";

    const promise = delay(1_000);

    // Rejects with `DOMException` after 100 ms
    await assertRejects(
    () => abortable(promise, AbortSignal.timeout(100)),
    DOMException,
    "Signal timed out."
    );
    import { abortable, delay } from "@std/async";
    import { assertRejects, assertEquals } from "@std/assert";

    const promise = delay(1_000);
    const controller = new AbortController();
    controller.abort(new Error("This is my reason"));

    // Rejects with `DOMException` immediately
    await assertRejects(
    () => abortable(promise, controller.signal),
    Error,
    "This is my reason"
    );
  • Make an AsyncIterable abortable with the given signal.

    Type Parameters

    • T

      The type of the provided and returned async iterable.

    Parameters

    • p: AsyncIterable<T, any, any>

      The async iterable to make abortable.

    • signal: AbortSignal

      The signal to abort the promise with.

    Returns AsyncGenerator<T>

    An async iterable that can be aborted.

    If the signal is already aborted and signal.reason is undefined. Otherwise, throws signal.reason.

    import { abortable, delay } from "@std/async";
    import { assertRejects, assertEquals } from "@std/assert";

    const asyncIter = async function* () {
    yield "Hello";
    await delay(1_000);
    yield "World";
    };

    const items: string[] = [];
    // Below throws `DOMException` after 100 ms and items become `["Hello"]`
    await assertRejects(
    async () => {
    for await (const item of abortable(asyncIter(), AbortSignal.timeout(100))) {
    items.push(item);
    }
    },
    DOMException,
    "Signal timed out."
    );
    assertEquals(items, ["Hello"]);
    import { abortable, delay } from "@std/async";
    import { assertRejects, assertEquals } from "@std/assert";

    const asyncIter = async function* () {
    yield "Hello";
    await delay(1_000);
    yield "World";
    };
    const controller = new AbortController();
    controller.abort(new Error("This is my reason"));

    const items: string[] = [];
    // Below throws `DOMException` immediately
    await assertRejects(
    async () => {
    for await (const item of abortable(asyncIter(), controller.signal)) {
    items.push(item);
    }
    },
    Error,
    "This is my reason"
    );
    assertEquals(items, []);