Skip to content

Instantly share code, notes, and snippets.

@bradoyler
Last active March 3, 2017 15:11
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 bradoyler/b71d83d08e084addc49c95d4e12d5e87 to your computer and use it in GitHub Desktop.
Save bradoyler/b71d83d08e084addc49c95d4e12d5e87 to your computer and use it in GitHub Desktop.
promise waterfall from collection
function promiseWaterfall(callbacks) {
var first = callbacks[0]();
return callbacks.slice(1).reduce(function (accumulator, callback) {
return accumulator.then(callback)
}, first)
}
var collection = [{id:'A'},{id:'B'},{id:'C'},{id:'D'}];
var promiseArray = collection.map(function(obj) {
return function fn() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log('### '+ obj.id + ' ' + new Date().getSeconds());
resolve(obj);
}, 1000);
});
});
promiseWaterfall(promiseArray)
.then(function (result) {
console.log(result)
});
// jsbin: http://jsbin.com/jazuku/edit?js,console
// output
//"### A 1"
//"### B 2"
//"### C 3"
//"### D 4"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment