Async Generator Fan-In Merges Sources

Race several async generators through one merged iterator: each source keeps its own next() promise and Promise.any picks whichever settles first.

JavascriptData Fetching

Code

javascriptsnippet
51 lines
// Fan-in: several async generators feed one merged iterator. Each source
// keeps its own pending next() promise; Promise.any takes whoever settles
function mergeAsync(generators) {
  const entries = generators.map((gen, index) => ({
    gen,
    index,
    pending: gen.next().then((step) => ({ step, index })),
  }));

  async function* merged() {
    const racing = new Set(entries);
    while (racing.size > 0) {
      const { step, index } = await Promise.any(
        [...racing].map((entry) => entry.pending),
      );
      const entry = entries[index];
      if (step.done) {
        racing.delete(entry); // this source is exhausted, stop racing it
      } else {
        yield step.value;
        entry.pending = entry.gen.next().then((next) => ({ step: next, index }));
      }
    }
  }
  return merged();
}

function ticker(name, items, delayMs) {
  async function* run() {
    for (const item of items) {
      await new Promise((resolve) => setTimeout(resolve, delayMs));
      yield name + ':' + item;
    }
  }
  return run();
}

async function main() {
  const merged = mergeAsync([
    ticker('a', ['1', '2'], 20),
    ticker('b', ['x', 'y'], 40),
    ticker('c', ['only'], 60), // exhausts after one item
  ]);

  for await (const value of merged) {
    console.log('merged:', value);
  }
  console.log('all sources exhausted');
}

main();

Output

Captured from a sandboxed run of this snippet in the build pipeline.

merged: a:1
merged: b:x
merged: a:2
merged: c:only
merged: b:y
all sources exhausted

How the snippet works

Async Generator Fan-In Merges Sources is built around the functions mergeAsync, ticker and main.

The nesting pairs while (racing.size > 0) with for (const item of items) — the inner runs once per outer step. Every asynchronous step is awaited, so rejections surface where the call happens.

Applying it

The primary signature is function mergeAsync(generators)

Expect labeled output — merged:, all sources exhausted — when the file runs.

main sequences mergeAsync and ticker; executing the file runs that flow once.

Statements that matter

await new Promise((resolve) => setTimeout(resolve, delayMs));
entry.pending = entry.gen.next().then((next) => ({ step: next, index }));
const { step, index } = await Promise.any(
  [...racing].map((entry) => entry.pending),
);

FAQ

What does Async Generator Fan-In Merges Sources print when run?
Running the file directly is enough — expect labeled output lines such as `merged:`, `all sources exhausted`.