仍然围绕着回调。
在回调函数中定义/返回对象的正确方法是什么?
你可以在下面的代码片段中看到我的2个console.logs,回调之外的那个当然是未定义的,我该如何定义呢?
在我的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});
});
我有以下效用函数可以正常工作:
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);
});
}
};
答案 0 :(得分:4)
你不应该这样做。回调应该是异步的,因此调用getMyGameQs之后的代码有可能在回调之前执行。
你应该做什么从回调内部调用“res.render”。
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});
});
});