Skip to content

Instantly share code, notes, and snippets.

@justforuse
Last active September 8, 2021 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justforuse/b8ecf4ed2fe113db643d52cbc11f626f to your computer and use it in GitHub Desktop.
Save justforuse/b8ecf4ed2fe113db643d52cbc11f626f to your computer and use it in GitHub Desktop.
Promise async pool with limit
Promise.limitAll = function(promises, limit) {
return new Promise(resolve => {
let resolvedCount = 0;
let count = 0;
let res = [];
const len = promises.length;
function next(p, index) {
p().then(r => {
res[index] = r;
// succeed count
resolvedCount ++
// still exist promise
if (promises.length) {
const p = promises.shift()
next(p, count)
count ++
} else if(resolvedCount === len) {
resolve(res)
}
})
}
// start limit number promises or all
while (count < limit && promises.length) {
const p = promises.shift()
next(p, count)
count ++
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment