我是node.js的新手,所以请耐心等待。
我想知道将模型传递给节点中的控制器的正确方法是什么。我有点工作但是当我从我的控制器中的模型中调用一个方法时,我从模型中返回的是“未定义的”#39;而且我不确定为什么。我与DB的连接很好。看看我的文件并查看我的评论。
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;
我做错了什么?提前致谢。
答案 0 :(得分:1)
正如NG所指出的,你的问题是asyc代码。 返回行返回行,只有你永远不会捕获它。
要解决此问题,您可以了解承诺,或潜入回调地狱。
如果选择回调地狱,它将如下所示:
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;