Last active
March 20, 2023 18:21
-
-
Save semlinker/a3de18ab4c8b95d1f4ed6d3f70f2131b to your computer and use it in GitHub Desktop.
async-pool-es7
This file contains hidden or 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 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why not using
p.finally(clean);
instead of
p.then(clean).catch(clean);
?