Skip to content

Instantly share code, notes, and snippets.

@semlinker
Last active July 25, 2022 10:19
Show Gist options
  • Save semlinker/1bc1dfdf3d089fddf19d7c426024ba09 to your computer and use it in GitHub Desktop.
Save semlinker/1bc1dfdf3d089fddf19d7c426024ba09 to your computer and use it in GitHub Desktop.
Promise
function asyncPool(concurrency, iterable, iteratorFn) {
let i = 0;
const ret = []; // // Store all asynchronous tasks
const executing = new Set(); // Stores executing asynchronous tasks
const enqueue = function() {
if (i === iterable.length) {
return Promise.resolve();
}
const item = iterable[i++]; // Get the new task item
const p = Promise.resolve().then(() => iteratorFn(item, iterable));
ret.push(p);
executing.add(p);
const clean = () => executing.delete(p);
p.then(clean).catch(clean);
let r = Promise.resolve();
if (executing.size >= concurrency) {
r = Promise.race(executing);
}
// The new to-do task will be obtained from the array only
// after the faster task in the executing task list is completed.
return r.then(() => enqueue());
};
return enqueue().then(() => Promise.all(ret));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment