nenne
nenne

Reputation: 165

Pass function to next function, fire depending on condition. nodejs

Im using express.js to create a node.js REST server, as a part o this i am also creating a simple session system. I have 3 modules:

The app.js url for http://localhost/api/highscores now calls userSession with given parameters:

//Get all highscores
app.get('/api/highscores', function (req, res) {
  userSession.checkValidity(req.query['username'], req.query['sessionid'], highscoreMan.getAll(req, res));
});

However, in checkValidity the function that i pass is automatically called:

function checkValidity(username, sessionId, callback) {
  userSession.findOne({ userid: username, sessionid: sessionId }, function (err, result) {
        if (err) {
          console.log(err);
        }
        if(result) {
          callback;
        }
  });
}

I only want to run the function being passed given that i get the proper results from the database(other checks will be added later for session dates etc.). How would i do this?

Upvotes: 1

Views: 2909

Answers (2)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123473

To delay calling highscoreMan.getAll(), you'll need to make it a statement of another function that can be called later:

app.get('/api/highscores', function (req, res) {
  userSession.checkValidity(req.query['username'], req.query['sessionid'], function () {
    highscoreMan.getAll(req, res);
  });
});

Otherwise, it's being called immediately and its return value is instead being passed to userSession.checkValidity().

Note that you'll also need to adjust checkValidity to call the passed callback:

// ...
if(result) {
  callback();
}
// ...

Upvotes: 2

pdoherty926
pdoherty926

Reputation: 10349

Unless I don't fully understand your problem, couldn't you just do something like this?

if (result && some_validator(result)) {
    callback();
}

Upvotes: 0

Related Questions