Skip to content

Instantly share code, notes, and snippets.

@zbitname
Created May 13, 2018 09:28
Show Gist options
  • Save zbitname/37699a44c93a38410a0cf04b46ff10dc to your computer and use it in GitHub Desktop.
Save zbitname/37699a44c93a38410a0cf04b46ff10dc to your computer and use it in GitHub Desktop.
JS
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