Skip to content

Instantly share code, notes, and snippets.

@Bamieh
Created July 20, 2016 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bamieh/67c9ca982b20cc33c9766d20739504c8 to your computer and use it in GitHub Desktop.
Save Bamieh/67c9ca982b20cc33c9766d20739504c8 to your computer and use it in GitHub Desktop.
Promise Waterfall for dynamic number of promises with callback on each and array resolve on complete
var counter = 0;
function run(cb) {
counter++;
return (function(count) {
return new Promise(function(resolve, reject) {
cb(count);
resolve(count);
});
})(counter);
}
var promises = {
onEach: function(fn){
var testArray = ["1"];
return testArray.reduce(function (acc) {
return acc.then(function (res) {
return boot(res, fn);
});
}, Promise.resolve([]));
}
}
function boot(res, fn) {
return run(fn).then(function(result) { // fetch from algolia
res.push(result);
if(result < 3) { // if cursor
return boot(res, fn);
}
return res;
})
}
promises
.onEach(function(count) {
console.log('onEach', count);
})
.then(function(total) {
console.log('total: ', total)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment