Raw
1 import { promiseAll } from "./promise-all"
2
3 /**
4 * Execute functions with a concurrency limit
5 * @param functions Array of functions to execute in parallel
6 * @param concurrency Maximum number of concurrent executions
7 */
8 export async function executeWithConcurrency<T>(
9 functions: (() => Promise<T>)[],
10 concurrency: number
11 ): Promise<PromiseSettledResult<Awaited<T>>[]> {
12 const functionsLength = functions.length
13 const results: PromiseSettledResult<Awaited<T>>[] = new Array(functionsLength)
14 let currentIndex = 0
15
16 const executeNext = async (): Promise<void> => {
17 while (currentIndex < functionsLength) {
18 const index = currentIndex++
19 const result = await Promise.allSettled([functions[index]()])
20 results[index] = result[0]
21 }
22 }
23
24 const workers: Promise<void>[] = []
25 for (let i = 0; i < Math.min(concurrency, functionsLength); i++) {
26 workers.push(executeNext())
27 }
28
29 await promiseAll(workers)
30
31 return results
32 }