Last active
July 25, 2022 10:19
-
-
Save semlinker/1bc1dfdf3d089fddf19d7c426024ba09 to your computer and use it in GitHub Desktop.
Promise
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
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