javascript / expert
Snippet
Complex Event Stream Filtering via Async Generator Control Flow
Async generators provide declarative control-flow primitives for processing asynchronous data streams. By pairing for await...of with conditional yield, you can compose clean async stream transformation pipelines.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
async function* filterStream(source, predicate) {for await (const item of source) {if (await predicate(item)) {yield item;}}}const numbers = async function* () { yield 5; yield 12; yield 8; }();const evenStream = filterStream(numbers, async (x) => x % 2 === 0);for await (const val of evenStream) {console.log(val);}
nodejs
Breakdown
1
async function* filterStream(source, predicate)
Defines an asynchronous generator function that creates an iterable stream transformer.
2
for await (const item of source)
Consumes asynchronous iterable items sequentially as they become available from the source stream.
3
yield item;
Emits filtered elements downstream back to the consumer while maintaining backpressure control.