Last active
March 3, 2017 15:11
-
-
Save bradoyler/b71d83d08e084addc49c95d4e12d5e87 to your computer and use it in GitHub Desktop.
promise waterfall from collection
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 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