Exercise 15: Promise Pool (limit concurrent)

Problem Statement

Function `createPool(size)` banao jo concurrent promises ko limit kare. Example: pool.add(() => fetchAPI1()); pool.add(() => fetchAPI2()); max size concurrent

Sample Output:

const pool = createPool(2);
pool.add(() => fetchAPI1()); pool.add(() => fetchAPI2());
// Max 2 concurrent

Solution

const createPool = (size) => {
  const queue = [];
  let running = 0;
  const process = async () => {
    if (running >= size || queue.length === 0) return;
    running++;
    const {fn, resolve, reject} = queue.shift();
    try { resolve(await fn()); } catch (err) { reject(err); }
    finally { running--; process(); }
  };
  return {add: (fn) => new Promise((res, rej) => { queue.push({fn, resolve: res, reject: rej}); process(); })};
};

Explanation

Overall Goal:

  • Concurrent promises ko limit karna.

Real world:

  • Rate limiting: concurrent requests.
  • Resource management: limit parallelism.