Created
June 30, 2022 13:33
-
-
Save pundoo/b3dca91487b6fa190a418647e74ae949 to your computer and use it in GitHub Desktop.
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* asyncPool(concurrency, iterable, iteratorFn) { | |
const executing = new Set(); | |
async function consume() { | |
const [promise, value] = await Promise.race(executing); | |
executing.delete(promise); | |
return value; | |
} | |
for (const item of iterable) { | |
// Wrap iteratorFn() in an async fn to ensure we get a promise. | |
// Then expose such promise, so it's possible to later reference and | |
// remove it from the executing pool. | |
const promise = (async () => await iteratorFn(item, iterable))().then( | |
value => [promise, value] | |
); | |
executing.add(promise); | |
if (executing.size >= concurrency) { | |
yield await consume(); | |
} | |
} | |
while (executing.size) { | |
yield await consume(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment