JavaScript

Promise All with Concurrency Limit

by @admin
10h ago
Apr 28, 2026
Public
Runs an array of async tasks with a maximum concurrency cap, preventing you from firing hundreds of requests simultaneously. Processes items in batches, moving to the next as slots free up. Essential when hitting rate-limited APIs or processing large datasets without overwhelming the server.
JavaScript
async function pLimit(tasks, limit = 5) {
  const results = [];
  const executing = new Set();

  for (const task of tasks) {
    const p = Promise.resolve().then(task).then((r) => {
      executing.delete(p);
      return r;
    });
    executing.add(p);
    results.push(p);
    if (executing.size >= limit) {
      await Promise.race(executing);
    }
  }
  return Promise.all(results);
}

// Usage
const urls = Array.from({ length: 20 }, (_, i) => `/api/item/${i}`);
const tasks = urls.map((url) => () => fetch(url).then((r) => r.json()));
const data = await pLimit(tasks, 4); // max 4 concurrent
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.