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

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

Problem

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:

  • app.js
  • highscoreMan.js
  • userSession.js

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?

Problem courtesy of: nenne

Solution

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();
}
// ...
Solution courtesy of: Jonathan Lonowski

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *