Function abortable
- abortable<T>(p, signal): Promise<T>
Type Parameters
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.
Throws
If the signal is already aborted and
signal.reasonis undefined. Otherwise, throwssignal.reason.Example: Error-handling a timeout
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."
);Example: Error-handling an abort
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"
);- p: Promise<T>
- abortable<T>(p, signal): AsyncGenerator<T>
Make an AsyncIterable abortable with the given signal.
Type Parameters
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.
Throws
If the signal is already aborted and
signal.reasonis undefined. Otherwise, throwssignal.reason.Example: Error-handling a timeout
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"]);Example: Error-handling an abort
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, []);- p: AsyncIterable<T, any, any>
Make a Promise abortable with the given signal.