// Created on savesnippets.com ยท https://savesnippets.com/QobQ96GBAmF1wz export async function mapConcurrent( items: readonly T[], limit: number, fn: (item: T, index: number) => Promise, ): Promise { 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(); });