How do you run multiple async iterators concurrently and merge their results?
Short answer
There's no built-in merge, so you typically race each iterator's next() Promise against the others, yielding whichever resolves first and re-queuing that iterator's next call — libraries like RxJS provide this out of the box.
Advertisement
AModel answer
There's no built-in merge, so you typically race each iterator's next() Promise against the others, yielding whichever resolves first and re-queuing that iterator's next call — libraries like RxJS provide this out of the box.
async function* merge(...iters) {
const its = iters.map(i => i[Symbol.asyncIterator]());
const promises = its.map((it, i) => it.next().then(r => ({ i, r })));
// race, yield, and refill promises[i] in a loop
}Real-world example
Combining live updates from multiple WebSocket feeds into a single unified event stream.
Likely follow-ups
- Why is manual merging harder than it looks at first glance?
Related topics