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.
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.
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);
}b
a
c
dAt 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.