capypad
0 day streak
javascript / expert
Snippet

Backpressure Handling in Async Generators

Async generators provide a natural way to implement backpressure. By awaiting a promise inside the generator before yielding, you can signal to the producer that the consumer is not ready for more data, effectively managing flow control in asynchronous streams.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
async function* streamProcessor(source) {
for await (const chunk of source) {
if (needsThrottling()) {
await new Promise(r => setTimeout(r, 100)); // Simulate backpressure
}
yield transform(chunk);
}
}
 
const consumer = async () => {
for await (const data of streamProcessor(dataSource)) {
console.log(data);
}
};
Breakdown
1
async function* streamProcessor
Defines a generator that can await asynchronous operations between yields.
2
for await (const chunk of source)
Consumes an asynchronous iterator while respecting its timing.