Last active
October 4, 2017 22:13
-
-
Save JosePedroDias/76bbb68ade995751ffc6a2fbc2597ae9 to your computer and use it in GitHub Desktop.
map limit with promises. play with it here: https://jsbin.com/fazihoc
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 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(); | |
}); | |
} |
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 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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I just play with your idea, check this: https://gist.github.com/Anmo/cdf674e09644f24ea58bef327e8016b3