0 day streak
javascript / expert
Snippet

Bidirectional Async Generator Pipelines

Async generators are not just for streaming data out; they can receive data back through the .next(value) call. This enables complex, full-duplex communication patterns where the generator can pause and wait for external input to decide its next asynchronous action.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
async function* duplexProcessor() {
let request = yield 'INIT_OK';
while (request !== 'TERMINATE') {
const response = await fetch(`https://api.example.com/data/${request}`);
request = yield await response.json();
}
}
const engine = duplexProcessor();
await engine.next(); // Start generator
const result = await engine.next('id_101');
console.log(result.value);
nodejs
Breakdown
1
request = yield await response.json();
Yields the fetched data and assigns the next input from .next() to 'request'.
2
await engine.next('id_101');
Resumes the generator and injects the string as the result of the previous yield.