Last active
September 8, 2021 14:22
-
-
Save justforuse/b8ecf4ed2fe113db643d52cbc11f626f to your computer and use it in GitHub Desktop.
Promise async pool with limit
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
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