我是 node.js 的新手,所以请多多包涵。
我想知道将模型传递给 Node 中的 Controller 的正确方法是什么。我有点让它工作但是当我从我的 Controller 中的模型调用一个方法时,我从模型返回的是“未定义的”,我不确定为什么。我与数据库的连接很好。看看我的文件,看看我的评论都是大写的。
路由.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);
};
模型.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 代码上。 return rows 正在返回行,只是您永远不会捕捉到它。
要解决此问题,您可以了解 promises,或深入了解回调 hell 。
如果你选择回调 hell ,它看起来像这样:
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;
和模型.js
function IndexModel(dbConnection) {
modelMethods = {};
modelMethods.getAllUsers = function(cb) {
var query = "SELECT * FROM `users`";
dbConnection.query(query, cb);
};
return modelMethods;
}
module.exports = IndexModel;
关于javascript - node.js/express js模型与 Controller 交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34865659/