Last active
June 21, 2021 05:44
-
-
Save MinweiShen/421cff4114816f4e8b54fcca64ca158f to your computer and use it in GitHub Desktop.
asyncPool.js
This file contains 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(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