DS
Back to JavaScript

promise-pool.js

javascript/async/promise-pool.js
JavaScript

Concurrency-limited promise pool — run N promises at a time from a queue.

promise-pool.js
/**
 * @description Concurrency-limited promise pool — run N promises at a time from a queue.
 * @tags async, promise, concurrency, pool
 */
export async function promisePool(tasks, concurrency = 3) {
  const results = [];
  const executing = new Set();

  for (const [index, task] of tasks.entries()) {
    const p = Promise.resolve().then(() => task()).then((result) => {
      results[index] = { status: "fulfilled", value: result };
    }).catch((error) => {
      results[index] = { status: "rejected", reason: error };
    }).finally(() => {
      executing.delete(p);
    });

    executing.add(p);

    if (executing.size >= concurrency) {
      await Promise.race(executing);
    }
  }

  await Promise.all(executing);
  return results;
}