TypeScript

Concurrency Limiter (semaphore)

admin by @admin ADMIN
3d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Run an array of async tasks but limit concurrency to N at a time — like p-limit, in 30 lines. Preserves input order in the output array.
TypeScript
Raw
export async function mapConcurrent<T, R>(
  items: readonly T[],
  limit: number,
  fn: (item: T, index: number) => Promise<R>,
): Promise<R[]> {
  const results: R[] = new Array(items.length);
  let next = 0;
  const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
    while (true) {
      const i = next++;
      if (i >= items.length) return;
      results[i] = await fn(items[i]!, i);
    }
  });
  await Promise.all(workers);
  return results;
}

// Fetch 100 URLs but only 5 in flight at a time.
const bodies = await mapConcurrent(urls, 5, async (url) => {
  return (await fetch(url)).text();
});
Tags

Save your own code snippets

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