Skip to content

Instantly share code, notes, and snippets.

@luojiyin1987
Created September 1, 2026 12:48
Show Gist options
  • Select an option

  • Save luojiyin1987/737b8596aa696c6b1cb7d359c4f4fa96 to your computer and use it in GitHub Desktop.

Select an option

Save luojiyin1987/737b8596aa696c6b1cb7d359c4f4fa96 to your computer and use it in GitHub Desktop.
runBounded.ts
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