node.js / express js模型和控制器之间的交互

我是node.js的新手,请耐心等待。

我想知道什么是正确的方式将模型传递给节点中的控制器。 我有点工作,但是当我从我的控制器中的模型调用一个方法,我从模型返回的是'未定义',我不知道为什么。 我的连接数据库是好的。 看看我的文件,看到我的意见全部大写。

routes.js

module.exports = function(app, dbConnection) { var theIndexModel = require('../models/index.server.models')(dbConnection); var index = require('../controllers/index.server.controller')(theIndexModel); app.get('/', index.homePage); }; 

models.js

 function IndexModel(dbConnection) { modelMethods = {}; modelMethods.getAllUsers = function(req, res) { var query = "SELECT * FROM `users`"; dbConnection.query(query, function(err, rows, fields) { return rows; //NOT RETURNING ANYTHING WHEN I CALL FROM CONTOLLER!! }); }; return modelMethods; } module.exports = IndexModel; 

controller.js

 function IndexController(theIndexModel) { controllerMethods = {}; controllerMethods.homePage = function(req, res) { console.log(theIndexModel.getAllUsers()); //UNDEFINED HERE, WHEN I SHOULD BE GETTING USERS FROM THE DB res.render('index', { title: 'hello' }); }; // Return the object that holds the methods. return controllerMethods; } module.exports = IndexController; 

我究竟做错了什么? 提前致谢。

正如NG指出的那样,你的问题是用asyc代码。 返回行是返回行,只有你是从来没有赶上它。

要解决这个问题,你可以了解承诺,或潜入callback地狱。

如果你selectcallback地狱,它会看起来像这样:

controller.js

 function IndexController(theIndexModel) { controllerMethods = {}; controllerMethods.homePage = function(req, res) { theIndexModel.getAllUsers(function(err, rows, fields){ res.render('index', { title: 'hello, users: rows }); }); }; // Return the object that holds the methods. return controllerMethods; } module.exports = IndexController; 

和models.js

 function IndexModel(dbConnection) { modelMethods = {}; modelMethods.getAllUsers = function(cb) { var query = "SELECT * FROM `users`"; dbConnection.query(query, cb); }; return modelMethods; } module.exports = IndexModel;