Skip to content

Instantly share code, notes, and snippets.

@JosePedroDias
Last active October 4, 2017 22:13
Show Gist options
  • Save JosePedroDias/76bbb68ade995751ffc6a2fbc2597ae9 to your computer and use it in GitHub Desktop.
Save JosePedroDias/76bbb68ade995751ffc6a2fbc2597ae9 to your computer and use it in GitHub Desktop.
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
Copy link

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