Last active
April 4, 2022 09:02
-
-
Save mmyoji/b1fea6fc5726b7154a395ac0a63bc1fa to your computer and use it in GitHub Desktop.
Run concurrent tasks with limit in TypeScript
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
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