k00k
k00k

Reputation: 17573

Node.js: How to properly return an object from within a callback?

Still wrapping my head around callbacks.

What's the proper way to define/return an object from within a callback function?

You can see my 2 console.logs in the following snippet, the one outside of the callback is of course undefined, how do I define it?

In my app.js:

  var tools = require('../models/tools.js');
  app.get('/games', requireAuth, function (req, res) {
    var gameqlist = tools.getMyGameQs(req, function(err, gameqlist){
      console.log(gameqlist); // this is properly defined
      return gameqlist; // not quite right
    });
    console.log(gameqlist); // this is undefined
    res.render('games', {title:'Your Games!', gameqlist : gameqlist});


  });

I have the following utility function which works fine:

tools.js:

var Gameq = require('../models/gameq');

module.exports = {
  getMyGameQs: function (req, callback){
    // find all game queues that a user is in
    Gameq
      .find({
                'game.players.player_id' : req.user.id
                })
      .asc('created_at') // sort by date - get oldest first
      .run(function(err, gameqlist) {
        if(!gameqlist){
          err = 'You are not in any games.';
        }
        return callback(err, gameqlist); 
      });
  }
};

Upvotes: 4

Views: 8317

Answers (1)

nxt
nxt

Reputation: 1983

You shouldn't want to do that. Callbacks are supposed to be asynchronous, so there is a chance that the code after the call to getMyGameQs is executed before the callback.

What you should do call "res.render" from inside the callback.

var tools = require('../models/tools.js');
  app.get('/games', requireAuth, function (req, res) {
    var gameqlist = tools.getMyGameQs(req, function(err, gameqlist){
      res.render('games', {title:'Your Games!', gameqlist : gameqlist});
    });
  });

Upvotes: 4

Related Questions