typescript / expert
Snippet
Cancellable Async Generator Queue with AbortSignal Handling
Async generators combined with AbortSignal provide explicit flow control and early cancellation capabilities for asynchronous streams. By checking signal.aborted before yielding each item, resource consumption can be cut off immediately when downstream consumers signal cancellation.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
async function* streamWithAbort<T>(source: AsyncIterable<T>,signal: AbortSignal): AsyncGenerator<T, void, unknown> {for await (const item of source) {if (signal.aborted) {throw new DOMException("Stream processing aborted by caller", "AbortError");}yield item;}}
Breakdown
1
async function* streamWithAbort<T>(
Declares a generic asynchronous generator function producing values of type T.
2
source: AsyncIterable<T>,
Accepts an asynchronous iterable input stream.
3
signal: AbortSignal
Receives a native AbortSignal object for cancellation monitoring.
4
): AsyncGenerator<T, void, unknown> {
Defines return type signatures for yielded values, return value, and next argument.
5
for await (const item of source) {
Asynchronously iterates over each item in the incoming stream.
6
if (signal.aborted) {
Checks if the cancellation signal has been triggered prior to processing.
7
throw new DOMException("Stream processing aborted by caller", "AbortError");
Throws a standardized AbortError to halt processing immediately.
8
yield item;
Yields the valid stream item to the consumer.