[READ-ONLY] a fast, modern browser for the npm registry
at main 37 lines 1.1 kB view raw
1/** 2 * Async utilities for controlled concurrency and parallel execution. 3 */ 4 5/** 6 * Map over an array with limited concurrency. 7 * Similar to Promise.all but limits how many promises run simultaneously. 8 * 9 * @param items - Array of items to process 10 * @param fn - Async function to apply to each item 11 * @param concurrency - Maximum number of concurrent operations (default: 10) 12 * @returns Array of results in the same order as input 13 * 14 * @example 15 * const results = await mapWithConcurrency(urls, fetchUrl, 5) 16 */ 17export async function mapWithConcurrency<T, R>( 18 items: T[], 19 fn: (item: T, index: number) => Promise<R>, 20 concurrency = 10, 21): Promise<R[]> { 22 const results: R[] = Array.from({ length: items.length }) as R[] 23 let currentIndex = 0 24 25 async function worker(): Promise<void> { 26 while (currentIndex < items.length) { 27 const index = currentIndex++ 28 results[index] = await fn(items[index]!, index) 29 } 30 } 31 32 // Start workers up to concurrency limit 33 const workers = Array.from({ length: Math.min(concurrency, items.length) }, () => worker()) 34 await Promise.all(workers) 35 36 return results 37}