仍圍繞着回調包裹我的頭。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