Skip to content

Instantly share code, notes, and snippets.

@semlinker
Last active March 20, 2023 18:21
Show Gist options
  • Save semlinker/a3de18ab4c8b95d1f4ed6d3f70f2131b to your computer and use it in GitHub Desktop.
Save semlinker/a3de18ab4c8b95d1f4ed6d3f70f2131b to your computer and use it in GitHub Desktop.
async-pool-es7
async function asyncPool(concurrency, iterable, iteratorFn) {
const ret = []; // Store all asynchronous tasks
const executing = new Set(); // Stores executing asynchronous tasks
for (const item of iterable) {
// Call the iteratorFn function to create an asynchronous task
const p = Promise.resolve().then(() => iteratorFn(item, iterable));
ret.push(p); // save new async task
executing.add(p); // Save an executing asynchronous task
const clean = () => executing.delete(p);
p.then(clean).catch(clean);
if (executing.size >= concurrency) {
// Wait for faster task execution to complete
await Promise.race(executing);
}
}
return Promise.all(ret);
}
@sg-gs
Copy link

sg-gs commented Mar 20, 2023

Why not using
p.finally(clean);
instead of
p.then(clean).catch(clean);
?

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