Run promises with a concurrency limit

Javascript

Keeps a fixed number of jobs in flight rather than firing a thousand requests at once.

async function pool(items, limit, worker) {
  const results = [];
  const running = new Set();
  for (const item of items) {
    const p = Promise.resolve().then(() => worker(item));
    results.push(p);
    running.add(p);
    p.finally(() => running.delete(p));
    if (running.size >= limit) await Promise.race(running);
  }
  return Promise.all(results);
}

More in JavaScript

Random picks