javascript - node.js/express js模型与 Controller 交互

标签 javascript node.js express model-view-controller

我是 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/

相关文章:

node.js - 如何处理 node.js/express 中的相对路径?

javascript - 如何在列表内添加到onclick函数,即<li onclick =””> <button onclick =””> </button> </li>

javascript - 了解AngularJS $ compile函数

javascript - 几乎所有地方都可以使用 async/await 吗?

javascript - 为什么 async await 和 Promise.all 的运行时间相同?

node.js - (NodeJS) Express 仅使用 Connect 提供了什么?

angularjs - 如果任何集合的文档超过 100 个,MEAN stack 应用程序将停止工作

javascript - 摆脱切换时的打嗝

javascript - 如何在Nogray时间选择器输入中调整宽度?

javascript - Date.now() 返回错误的日期