pstream is dead; long live pstream taciturnaxolotl.github.io/pstream-ng/
at main 32 lines 943 B view raw
1/** 2 * Maps an array to a promise that resolves with an array of results, 3 * limiting the number of concurrent operations. 4 * 5 * @param items The array of items to map 6 * @param concurrency The maximum number of concurrent operations 7 * @param fn The async function to apply to each item 8 * @returns A promise that resolves with an array of results 9 */ 10export async function concurrentMap<T, R>( 11 items: T[], 12 concurrency: number, 13 fn: (item: T) => Promise<R>, 14): Promise<R[]> { 15 const results: R[] = new Array(items.length); 16 const queue = items.map((item, index) => ({ item, index })); 17 18 const workers = Array.from( 19 { length: Math.min(concurrency, items.length) }, 20 async () => { 21 while (queue.length > 0) { 22 const entry = queue.shift(); 23 if (!entry) break; 24 const { item, index } = entry; 25 results[index] = await fn(item); 26 } 27 }, 28 ); 29 30 await Promise.all(workers); 31 return results; 32}