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();
});
Create a free account and build your private vault. Share publicly whenever you want.