Created
September 1, 2026 12:48
-
-
Save luojiyin1987/737b8596aa696c6b1cb7d359c4f4fa96 to your computer and use it in GitHub Desktop.
runBounded.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export async function runBounded<T>( | |
| tasks: Array<() => Promise<T>>, | |
| concurrency: number | |
| ): Promise<T[]> { | |
| const results: T[] = new Array(tasks.length); | |
| let nextIndex = 0; | |
| let failed = false; | |
| async function runner() { | |
| while (!failed) { | |
| const index = nextIndex++; | |
| if (index >= tasks.length) { | |
| return; | |
| } | |
| try { | |
| results[index] = await tasks[index](); | |
| } catch (error) { | |
| failed = true; | |
| throw error; | |
| } | |
| } | |
| } | |
| const runners = Array.from( | |
| { | |
| length: Math.min( | |
| concurrency, | |
| tasks.length | |
| ), | |
| }, | |
| runner | |
| ); | |
| await Promise.all(runners); | |
| return results; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment