Created
September 1, 2016 14:47
-
-
Save huang-x-h/af13fdfceb00b93d6fa0165f6cee26eb to your computer and use it in GitHub Desktop.
Promise.eachLimit
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 createArrayIterator(coll) { | |
var i = -1; | |
var len = coll.length; | |
return function next() { | |
return ++i < len ? {value: coll[i], key: i} : null; | |
} | |
} | |
function eachLimit(coll, limit, iteratee) { | |
if (limit <= 0 || !coll) return Promise.resolve(); | |
var done = false; | |
var running = 0; | |
var nextElem = createArrayIterator(coll); | |
function replenish() { | |
return new Promise(function(resolve, reject) { | |
while (running < limit && !done) { | |
var elem = nextElem(); | |
if (elem === null) { | |
done = true; | |
if (running <= 0) { | |
resolve(); | |
} | |
return; | |
} | |
running++; | |
iteratee(elem.value, elem.key).then(function() { | |
running--; | |
if (done && running <= 0) { | |
resolve(); | |
} else { | |
replenish().then(resolve, reject) | |
} | |
}).catch(function(e) { | |
running--; | |
done = true; | |
reject(e); | |
}); | |
} | |
}); | |
} | |
return replenish(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment