Skip to content
jshacks.dev
Async

Map an async iterator with a concurrency limit

Map an async iterator with a concurrency limit in JavaScript: keep up to N mapped promises running and yield results as they finish.

1 min read
Summarize in AI

You have a stream of items and a slow async step for each. A generator can keep a fixed number of calls running and yield results as they finish.

JavaScript
const delay = (ms, v) => new Promise((r) => setTimeout(r, ms, v));

async function* mapLimit(source, fn, limit) {
  const running = new Set();
  const track = (promise) => {
    const tracked = promise.then((value) => {
      running.delete(tracked);
      return value;
    });
    running.add(tracked);
  };
  for await (const item of source) {
    track(fn(item));
    if (running.size >= limit) yield await Promise.race(running);
  }
  while (running.size > 0) yield await Promise.race(running);
}

const ms = { a: 30, b: 10, c: 25, d: 10 };
async function* items() {
  yield* Object.keys(ms);
}

for await (const result of mapLimit(items(), (key) => delay(ms[key], key), 2)) {
  console.log(result);
}
Text
b
a
c
d

At most two calls run at once. a and b start first, b finishes at 10 ms and is yielded, which frees a slot for c. Results come out in completion order, not input order, which is why b precedes a.

The generator reads the next item only after the consumer asks for the next result, so a slow consumer slows the source down. If a mapped call rejects, the generator throws on the next race and the remaining calls continue unobserved.

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.