user2727195 user2727195 - 5 months ago 26
Javascript Question

passing parameters to functions returning promises in a chain

I've a bunch of functions expecting parameters and returning promises, not sure how can I pass individual params to each one in the chain.

fs.readFile('./img/thumbnail.png', function(error, data) {
module.create(body)
.then(module.uploadImage) //expects collection.uploadImage(data);
.then(module.requestInfo)
});


How can I make promises pass
data
to
module.uploadImage
as the parameter?

Answer

If the data is known at the time you enter the function, you can use .bind():

fs.readFile('./img/thumbnail.png', function(error, data) {
    module.create(body)
        .then(module.uploadImage.bind(module, data))
        .then(module.requestInfo)
});

See the description of .bind() on MDN for more details.


You can of course, always just create your own wrapper function that lets you pass anything you want, including computed parameters:

fs.readFile('./img/thumbnail.png', function(error, data) {
    module.create(body).then(function() {
        return module.uploadImage(data);
    }).then(module.requestInfo)
});

P.S. Please don't ignore error checking on your fs.readFile() callback.

Comments