Skip to content

Instantly share code, notes, and snippets.

@MinweiShen
Last active June 21, 2021 05:44
Show Gist options
  • Save MinweiShen/421cff4114816f4e8b54fcca64ca158f to your computer and use it in GitHub Desktop.
Save MinweiShen/421cff4114816f4e8b54fcca64ca158f to your computer and use it in GitHub Desktop.
asyncPool.js
async function asyncPool(poolSize, inputArray, fn) {
const all = [];
const inProgress = [];
for (const data of inputArray) {
const p = new Promise(resolve => resolve(fn(data)));
all.push(p);
if (inputArray.length > poolSize) {
const e = p.then(() => inProgress.splice(inProgress.indexOf(p), 1));
inProgress.push(e);
if (inProgress.length >= poolSize) {
console.log('wait until at least one is done and the pool is available')
await Promise.race(inProgress);
}
}
}
return Promise.all(all);
}
asyncPool(2, [1, 2, 3], (i) => i * 2).then(r => console.log(r))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment