Run promises with a concurrency limit

Process many async jobs, but only N at a time.

javascript advanced #async#promises#performance
Open in playground
js-promise-pool.js
async function mapLimit(items, limit, worker) {
  const results = new Array(items.length);
  let next = 0;
  async function lane() {
    while (next < items.length) {
      const i = next++;
      results[i] = await worker(items[i], i);
    }
  }
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, lane));
  return results;
}

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
mapLimit([300, 100, 200, 50], 2, async (ms, i) => { await sleep(ms); return `job ${i} took ${ms}ms`; })
  .then((r) => console.log(r));