Created
November 13, 2021 20:22
-
-
Save Beaglefoot/a0c0a41b86440a99504c666ed3181ba8 to your computer and use it in GitHub Desktop.
Executes array of promise-returning functions with provided concurrency level
This file contains 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 Task<R> = () => Promise<R> | |
/** Execute array of promise-returning functions with provided concurrency level */ | |
async function* concurrentGen<R>(tasks: Task<R>[], concurrency: number) { | |
async function withIndex(task: Task<R>, index: number) { | |
const result = await task() | |
return { result, index } | |
} | |
const queues = tasks.splice(0, concurrency).map(withIndex) | |
while (queues.some(Boolean)) { | |
const { result, index } = await Promise.race(queues.filter(Boolean)) | |
const nextTask = tasks.shift() | |
if (nextTask) queues[index] = withIndex(nextTask, index) | |
else delete queues[index] | |
yield result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment