Rodmentou
Rodmentou

Reputation: 1640

How to pass in a variable to a .then() callback function from an outer scope?

I have an API receiving an request and doing some querys and validation.

I want to use the response reference from the route inside the findUserPlayer function so I can send something to the client. The findUser function will return a data object that will be used on findUserPlayer.

var api = express.Router();

api.post('/signup', function (request, response) {

    UserModel.find(req.body)
        .then(findUser, createUser)
        .then(findUserPlayer, createUserPlayer);
});

var findUserPlayer = function (data, res) {
    //...
    res.json(object);
};

How can I use the response object inside that callback?

Upvotes: 2

Views: 392

Answers (3)

Kunal Kapadia
Kunal Kapadia

Reputation: 3353

Instead of directly passing findUserPlayer function as a success handler, you can define a success handler function while will then call findUserPlayer.

var api = express.Router();

api.post('/signup', function (request, response) {

    UserModel.find(req.body)
        .then(findUser, createUser)
        .then(function(data) {
            return findUserPlayer(data, response);
        }, createUserPlayer);
});

var findUserPlayer = function (data, res) {
    //...
    res.json(object);
};

Upvotes: 1

Quy
Quy

Reputation: 1373

I'm a big fan of lodash and sometimes to a fault, but thought I would add the following using lodash's partialRight function.

var _ = require('lodash');
...
UserModel.find(req.body)
    .then(findUser, createUser)
    .then(_.partialRight(findUserPlayer, response), createUserPlayer);

_.partialRight returns a new function with the partials appended to the new function. The first argument of _.partialRight is the function we want to append the arguments to. The subsequent arguments are the args we want to append to the function.

I'm assuming the following function signature: findUserPlayer(data, response). _.partialRight appends the response object to the new function. The new function signature looks like this now: function (data).

documentation

Upvotes: 1

Amit
Amit

Reputation: 46351

JavaScript is a very flexible language which means there are many ways you can handle this, one of the easiest (in terms of minimum code change) is to reverse the order of arguments in findUserPlayer and binding your context (.bind(response)).

But that would be a poor design choice. There's no reason for a function that "finds a user" to deal with responses or json. It's out of this functions scope and responsibility. The request handler is the one that should deal with formatting a relevant response, and I'd do that by returning the relevant data in the promise chain and eventually:

.then(function(data) {
   response.json(data);
});

Upvotes: 1

Related Questions