Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
map limit with promises. play with it here: https://jsbin.com/fazihoc
function eachN(arr, n) {
const arr0 = arr.slice();
const arrs = [];
while (arr0.length > 0) {
arrs.push( arr0.splice(0, n) );
}
return arrs;
}
function mapLimit(arr, promFn, limit) {
const arrs = eachN(arr, limit);
let results = [];
return new Promise(function(resolve, reject) {
function step() {
const batch = arrs.shift();
if (!batch) { return resolve(results); }
Promise.all(batch.map(promFn))
.then(function(subRes) {
results = results.concat(subRes);
step();
})
.catch(function(err) {
reject(err);
});
}
step();
});
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function sleep2(n) {
return new Promise(resolve => {
console.log('FIRED ' + n);
sleep(500).then(() => {console.log(n); resolve(n); });
});
}
mapLimit([1,2,3,4,5,6,7], sleep2, 3).then(r => console.log(r));
@Anmo

This comment has been minimized.

Show comment
Hide comment
@Anmo

Anmo commented Oct 4, 2017

I just play with your idea, check this: https://gist.github.com/Anmo/cdf674e09644f24ea58bef327e8016b3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment