nodejs-无法从辅助函数中获取数据

nodejs- unable to fetch data from a helper function

我正在为我的项目使用 ExpressJS 4,它遵循 MVC 架构。 我创建了一个帮助器,我可以在其中编写常用函数,从数据库中查询数据(DRY 方法),并且可以从任何控制器访问这些函数。 我可以调用辅助函数并将数据传递给它,但我无法从中查询数据库。

这是我的控制器示例 (dumyController.js):

'use strict';
var dbHelpers = require('../helpers/helpers');

exports.dummyFunction = function (req, res) {
    var id=165;
    var abc = dbHelpers.dummyHelperFunction(iddd);
    console.log(abc);
};

如您所见,我正在调用控制器中的辅助函数。 这是助手的示例 (helpers.js)

var db = require('../db');
module.exports = {
  dummyHelperFunction: function (passvar) {
    var params = [passvar];
    var query = `SELECT email FROM members where id=?`;
    return db.query(query, params);
  }
};

如果您想知道我的数据库连接是否有问题,没有与此相关的问题。还是分享一下(db.js)

var mysql = require('mysql');
var connection = mysql.createPool({
    host: '127.0.0.1',
    user: 'root',
    password: '',
    database: 'dumyDB'
});
module.exports = connection;

我正在尝试获取 MySQL 查询返回的结果,但这是我 console.log 查询时得到的结果。

Query {
  domain: null,
  _events: {},
  _eventsCount: 0,
  _maxListeners: undefined,
  _callback: undefined,
  _callSite:
   Error
       at Pool.query (_PROJECT-PATH_\node_modules\mysql\lib\Pool.js:199:23)
       at Object.dummyHelperFunction (_PROJECT-PATH_\helpers\helpers.js:18:15)
       at exports.dummyFunction (_PROJECT-PATH_\controllers\dumyController.js:227:25)
       at Layer.handle [as handle_request] (_PROJECT-PATH_\node_modules\express\lib\router\layer.js:95:5)
       at next (_PROJECT-PATH_\node_modules\express\lib\router\route.js:137:13)
       at Route.dispatch (_PROJECT-PATH_\node_modules\express\lib\router\route.js:112:3)
       at Layer.handle [as handle_request] (_PROJECT-PATH_\node_modules\express\lib\router\layer.js:95:5)
       at _PROJECT-PATH_\node_modules\express\lib\router\index.js:281:22
       at Function.process_params (sam_PROJECT-PATH_ple\node_modules\express\lib\router\index.js:335:12)
       at next (_PROJECT-PATH_\node_modules\express\lib\router\index.js:275:10),
  _ended: false,
  _timeout: undefined,
  _idleNext: null,
  _idlePrev: null,
  _idleStart: null,
  _idleTimeout: -1,
  _repeat: null,
  sql: 'SELECT email FROM members where id=?',
  values: [ 165 ],
  typeCast: true,
  nestTables: false,
  _resultSet: null,
  _results: [],
  _fields: [],
  _index: 0,
  _loadError: null }

将您的代码更改为如下所示。 db.query() 是异步的

控制器

'use strict';
var dbHelpers = require('../helpers/helpers');
exports.dummyFunction = function (req, res) {
    var user = {
        passvar: 165
    };
    dbHelpers.dummyHelperFunction(user, function (err, rows) {
        if (err) {
            res.json({ success: false, message: 'unable to fetch' });
        }
        else {
            res.json({ success: true, values: rows });
        }
    });
};

帮手

var db = require('../db');
module.exports = {
  dummyHelperFunction: function (param, callback) {
    var params = [param.passvar];
    var query = `SELECT email FROM members where id=?`;
    return db.query(query, params, callback);
  }
};