Merge async iterators into one
Merge async iterators into one in JavaScript: race the next value of each source and yield whichever arrives first. Node.js 24.
You have two async sources, such as two feeds, and want one loop that handles items from both as they arrive. Race the next value of every source.
const delay = (ms) => new Promise((r) => setTimeout(r, ms));
async function* merge(...sources) {
const iterators = sources.map((s) => s[Symbol.asyncIterator]());
const pending = new Map(
iterators.map((it, i) => [i, it.next().then((result) => ({ i, result }))]),
);
while (pending.size > 0) {
const { i, result } = await Promise.race(pending.values());
if (result.done) {
pending.delete(i);
continue;
}
pending.set(i, iterators[i].next().then((r) => ({ i, result: r })));
yield result.value;
}
}
async function* ticker(name, ms, count) {
for (let k = 1; k <= count; k++) {
await delay(ms);
yield `${name}${k}`;
}
}
for await (const value of merge(ticker('a', 30, 2), ticker('b', 20, 2))) {
console.log(value);
}b1
a1
b2
a2The ticker b yields at 20 ms and 40 ms, and a at 30 ms and 60 ms, so the merged order is b1, a1, b2, a2. Each source keeps one next() call in flight, and the map holds the latest one per source. A source that finishes is removed.
This sketch does not close the sources when the consumer stops early with break. A production version calls return() on each iterator in a finally block.