Created
July 20, 2016 19:49
-
-
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
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
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