(
items: T[],
maxConcurrent: number,
cancellationToken: { isCancellationRequested: boolean },
task: (item: T) => Promise<void>,
onCompleted?: (completed: number, total: number, item: T) => void,
onStarted?: (item: T) => void,
)
| 21 | } |
| 22 | |
| 23 | export async function runWithConcurrencyLimit<T>( |
| 24 | items: T[], |
| 25 | maxConcurrent: number, |
| 26 | cancellationToken: { isCancellationRequested: boolean }, |
| 27 | task: (item: T) => Promise<void>, |
| 28 | onCompleted?: (completed: number, total: number, item: T) => void, |
| 29 | onStarted?: (item: T) => void, |
| 30 | ): Promise<void> { |
| 31 | if (!items.length) |
| 32 | return; |
| 33 | |
| 34 | const maxWorkers = Math.max(1, Math.min(maxConcurrent, items.length)); |
| 35 | let nextIndex = 0; |
| 36 | let completed = 0; |
| 37 | let firstError: unknown; |
| 38 | |
| 39 | /// A worker that continuously processes items until there are none left. |
| 40 | const worker = async () => { |
| 41 | while (!firstError && !cancellationToken.isCancellationRequested) { |
| 42 | // Grab the index of the next item. |
| 43 | const index = nextIndex++; |
| 44 | if (index >= items.length) |
| 45 | return; // All items are done. |
| 46 | |
| 47 | const item = items[index]; |
| 48 | onStarted?.(item); // Signal that we're starting. |
| 49 | |
| 50 | try { |
| 51 | await task(item); // Run the main task. |
| 52 | completed++; |
| 53 | onCompleted?.(completed, items.length, item); // Signal that we're done. |
| 54 | } catch (error) { |
| 55 | firstError ??= error; |
| 56 | return; |
| 57 | } |
| 58 | } |
| 59 | }; |
| 60 | |
| 61 | await Promise.all(Array.from({ length: maxWorkers }, () => worker())); |
| 62 | |
| 63 | if (firstError) |
| 64 | throw firstError; // eslint-disable-line @typescript-eslint/only-throw-error |
| 65 | } |
no test coverage detected