Create a gist now

Instantly share code, notes, and snippets.

Embed
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
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