I have created 4 different functions that return promises. By running the "hello" function and passing each subsequent function into the next .then
, you can generate a single long string output.
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
My goal is to pass an array of these functions into another function, which will then nest them all together into one final function.
var arr = wrapThen([
hello,
world,
foo,
bar
])
arr("alpha").then(console.log)
I am wondering if this type of nesting operation is possible, and if Bluebird offers any features for this.
Here is the solution I came up with:
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)
})
}
}