Skip to content

Instantly share code, notes, and snippets.

@pundoo
Created June 30, 2022 13:33
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 pundoo/b3dca91487b6fa190a418647e74ae949 to your computer and use it in GitHub Desktop.
Save pundoo/b3dca91487b6fa190a418647e74ae949 to your computer and use it in GitHub Desktop.
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