Skip to content

Instantly share code, notes, and snippets.

@mmyoji
Last active April 4, 2022 09:02
Show Gist options
  • Save mmyoji/b1fea6fc5726b7154a395ac0a63bc1fa to your computer and use it in GitHub Desktop.
Save mmyoji/b1fea6fc5726b7154a395ac0a63bc1fa to your computer and use it in GitHub Desktop.
Run concurrent tasks with limit in TypeScript
type TaskFn<T> = () => Promise<T>;
// see: https://maximorlov.com/parallel-tasks-with-pure-javascript/
async function limit<T>(tasks: TaskFn<T>[], concurrency: number) {
const results: (T | Error)[] = [];
async function run(iterator: IterableIterator<[number, TaskFn<T>]>) {
for (const [index, task] of iterator) {
try {
results[index] = await task();
} catch (error) {
results[index] = new Error(`Failed with: ${(error as Error).message}`);
}
}
}
const workers = new Array(concurrency).fill(tasks.entries()).map(run);
await Promise.allSettled(workers);
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment