Skip to content

Instantly share code, notes, and snippets.

@Beaglefoot
Created November 13, 2021 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Beaglefoot/a0c0a41b86440a99504c666ed3181ba8 to your computer and use it in GitHub Desktop.
Save Beaglefoot/a0c0a41b86440a99504c666ed3181ba8 to your computer and use it in GitHub Desktop.
Executes array of promise-returning functions with provided concurrency level
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