Created
October 2, 2017 22:32
-
-
Save JosePedroDias/d0346461d8c0a0398d84a6de2c71ca38 to your computer and use it in GitHub Desktop.
async map with promises :D each doesn't seem to work sync by the time we call the promise-returning function we're already starting it. I believed so but by runnign the example it gets obvious
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); }); | |
}); | |
} | |
// ------ | |
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 eachLimit(arr, 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) | |
.then(function(subRes) { | |
results = results.concat(subRes); | |
step(); | |
}) | |
.catch(function(err) { | |
reject(err); | |
}); | |
} | |
step(); | |
}); | |
} | |
mapLimit([1,2,3,4,5,6,7], sleep2, 3).then(r => console.log(r)); | |
//eachLimit( [sleep2(1), sleep2(2), sleep2(3)], 1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment