typescript / expert
Snippet
Asynchronous Generator Stream Pipelining with AbortSignal Cancellation
This snippet demonstrates build-in async stream processing using TypeScript's `AsyncGenerator` and native `AbortSignal`. It guarantees resource-safe cooperative cancellation and backpressure support when piping asynchronous data sequences without external libraries.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
async function* filterAsyncStream<T>(source: AsyncIterable<T>,predicate: (item: T) => boolean,signal?: AbortSignal): AsyncGenerator<T> {for await (const item of source) {if (signal?.aborted) {throw signal.reason ?? new Error("Operation aborted");}if (predicate(item)) {yield item;}}}
Breakdown
1
async function* filterAsyncStream<T>(
Declares an asynchronous generator producing values of type T.
2
source: AsyncIterable<T>,
Accepts any source complying with the standard AsyncIterable interface.
3
signal?: AbortSignal
Integrates standard AbortSignal for asynchronous task cancellation.
4
if (signal?.aborted) {
Checks cancellation status before processing each yielded item.
5
yield item;
Yields valid items matching the predicate condition back to the consumer.