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

Still wraps callbacks.

What is the correct way to define / return an object from a callback function?

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

In my app.js app:

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 that 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); }); } }; 
+4
source share
1 answer

You must not do this. Callbacks must be asynchronous, so there is a chance that the code after calling getMyGameQs will execute before the callback.

What you have to do is 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}); }); }); 
+4
source

Source: https://habr.com/ru/post/1389324/


All Articles