Here I have 4 functions that return promises. If you run hello and pass each on into the next .then you get one long string.
var hello = function(str){
return Promise.resolve(str+ "hello")
}
var world = function(str){
return Promise.resolve(str+ "world")
}
var foo = function(str){
return Promise.resolve(str+ "foo")
}
var bar = function(str){
return Promise.resolve(str+ "bar")
}
// hello("alpha").then(world).then(foo).then(bar).then(console.log)
// => alphahelloworldfoobar
I'd like to be able to pass a flat array of the functions into a function and get return a function that has them all nested.
var arr = wrapThen([
hello,
world,
foo,
bar
])
arr("alpha").then(console.log)
Is this possible? Does bluebird offer this?
This is what I hacked together:
function wrapThen(arr){
var headPromise = arr.shift()
return function(){
var args = _.values(arguments)
var init = headPromise(args)
var values = []
return Promise.each(arr, function(item){
init = init.then(item)
return init.then(function(value){
values.push(value)
return value
})
}).then(function(){
return _.last(values)
})
}
}