Skip to content
jshacks.dev
Async

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.

1 min read
Summarize in AI

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.

JavaScript
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);
}
Text
b1
a1
b2
a2

The 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.

Taggednode 24
Share

More snippets

Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.