Last active
August 12, 2016 11:47
-
-
Save frogcjn/3849281e91c3e9535b2e28b19cac40a8 to your computer and use it in GitHub Desktop.
Promise all with limited concurrency promise running
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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: This gist needs async await grammar support.