Created
May 13, 2018 09:28
-
-
Save zbitname/37699a44c93a38410a0cf04b46ff10dc to your computer and use it in GitHub Desktop.
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
function promiseLimit(data, promiseFncGenerator, limit) { | |
const dataLength = data.length; | |
let cursor = 0; | |
function next() { | |
if (cursor < dataLength) { | |
return promiseFncGenerator(data[cursor++]); | |
} | |
return null; | |
} | |
const results = []; | |
function getNextPromiseChain() { | |
const promise = next(); | |
if (promise) { | |
return promise.then(res => { | |
results.push(res); | |
if (res) { | |
const newPromise = getNextPromiseChain(); | |
if (newPromise) { | |
return newPromise; | |
} | |
} | |
return null; | |
}); | |
} | |
return null; | |
} | |
const promises = new Array(limit).fill(0).map(() => getNextPromiseChain()); | |
return Promise.all(promises).then(() => results); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment