Skip to content

Instantly share code, notes, and snippets.

@frogcjn
Last active August 12, 2016 11:47
Show Gist options
  • Save frogcjn/3849281e91c3e9535b2e28b19cac40a8 to your computer and use it in GitHub Desktop.
Save frogcjn/3849281e91c3e9535b2e28b19cac40a8 to your computer and use it in GitHub Desktop.
Promise all with limited concurrency promise running
async function limitedPromiseAll<T>(promises: (() => Promise<T>)[], limit: number) {
const promisesCopy = promises.slice()
const factory = function () {
return promisesCopy.shift()
}
const results: T[] = []
const pipelines: (() => Promise<T>)[] = []
while (pipelines.length < limit) {
const pipline = async () => {
let promise = factory()
while (promise) {
const result = await promise()
results.push(result)
promise = factory()
}
}
pipelines.push(pipline)
}
await Promise.all(pipelines.map(pipeline => pipeline()))
return results
}
@frogcjn
Copy link
Author

frogcjn commented Aug 12, 2016

Note: This gist needs async await grammar support.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment