abortable

import { abortable } from "jsr:@ende/async";

function

function abortable<T>(p: Promise<T>, signal: AbortSignal): Promise<T>

Make a Promise abortable with the given signal.

p: Promise<T>

The promise to make abortable.

signal: AbortSignal

The signal to abort the promise with.

Returns

A promise that can be aborted.

Example: Error-handling a timeout

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

const promise = delay(1_000);

// Rejects with `DOMException` (name `"TimeoutError"`) after 100 ms
const error = await assertRejects(
  () => abortable(promise, AbortSignal.timeout(100)),
  DOMException,
);
assertEquals(error.name, "TimeoutError");

Example: Error-handling an abort

import { abortable, delay } from "@ende/async";
import { assertRejects, assertEquals } from "@ende/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"
);

function

function abortable<T>(p: AsyncIterable<T>, signal: AbortSignal): AsyncGenerator<T>

Make an AsyncIterable abortable with the given signal.

p: AsyncIterable<T>

The async iterable to make abortable.

signal: AbortSignal

The signal to abort the promise with.

Returns

An async iterable that can be aborted.

Example: Error-handling a timeout

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

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

const items: string[] = [];
// Below throws `DOMException` (name `"TimeoutError"`) after 100 ms and items
// become `["Hello"]`
const error = await assertRejects(
  async () => {
    for await (const item of abortable(asyncIter(), AbortSignal.timeout(100))) {
      items.push(item);
    }
  },
  DOMException,
);
assertEquals(error.name, "TimeoutError");
assertEquals(items, ["Hello"]);

Example: Error-handling an abort

import { abortable, delay } from "@ende/async";
import { assertRejects, assertEquals } from "@ende/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, []);

function

function abortable<T>(p: Promise<T> | AsyncIterable<T>, signal: AbortSignal): Promise<T> | AsyncIterable<T>

Source