Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

Problem

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); 
      });
  }
};
Problem courtesy of: k00k

Solution

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});
    });
  });
Solution courtesy of: nxt

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×