仍围绕着回调包裹我的头。Node.js:如何正确地从回调中返回一个对象?
从回调函数中定义/返回对象的正确方法是什么?
你可以在下面的代码片段中看到我的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});
});
我有以下的效用函数的正常工作:
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);
});
}
};
我有同样的问题,并发现[此](https://stackoverflow.com/questions/25807786/separating-daos-from-controllers-for-reusability-purposes)是有用的。 – arymeo 2014-09-12 19:43:23