vitaly-t vitaly-t - 5 months ago 11
Javascript Question

Chaining results with Bluebird

Is there any convenience method in Bluebird for a resolution chain where the input for each element is the resolved value from the previous element (unless it is not a function)?

I'm trying to chain the following logic into a single method:

function getClient() {
// resolves with the client
}

function getClientProduct(client) {
// resolves with the product
}

var response = {}; // global response object;

function prepareResponse(product) {
// prepares global response object, resolves with `undefined`
}

promise.someMethod(getClient, getClientProduct, prepareResponse, response)
.then(data=> {
// data = the response object;
});


I'd like to avoid having to write the following (if possible):

getClient()
.then(client=>getClientProduct(client))
.then(product=>prepareResponse(product))
.then(()=>response);

Answer

Those arrow functions are meaningless. You can do simply

getClient().then(getClientProduct).then(prepareResponse).…

There is no convenience method to shorten that further - I guess you don't want to consider

[getClient, getClientProduct, prepareResponse].reduce((p,fn)=>p.then(fn), Promise.resolve())

For the last one, you can use the .return(response) utility method.