nodejs q无法解析

时间:2017-11-09 14:54:46

标签: node.js q

当我查询用户时,q将无法解析我的承诺(或者我的then-function将不会解析它)。我得到了所有的调试输出,直到我在用户控制器的then-function中获得调试输出。那里的调试输出就停止了。

当我尝试从用户模型中调用get时,解决方案没有问题。它刚刚解决好了。只有在退回到用户控制器时才会出现此问题。

用户控制器

var UserModel        = require('../model/user.model');

function UserController () {}

UserController.prototype.get = get;

function get (req, res, next) {

    UserModel.get('54c1b6c7-193e-4cb6-aa17-37d1f0a8fc7b').then(function (response) {
        debug(response);
        res.send('ok');
    }, function (response) {
        debug(response);
        res.send('not ok');
    });
}

module.exports = new UserController();

用户模型

var mysql       = require('mysql'),
    config      = require('config'),
    Q           = require('q'),
    debug       = require('debug')('user.model'),
    BaseModel   = require('./base.model'),
    connection  = mysql.createConnection({
        host     : config.get('database.host'),
        user     : config.get('database.user'),
        password : config.get('database.password'),
        database : config.get('database.database')
    }),
    sql;

function UserModel () {
    BaseModel.setConnection(connection);
}

UserModel.prototype.get = get;


function get(id) {
    var deferred = Q.defer();

    sql = 'SELECT * FROM users WHERE id LIKE ' + connection.escape(id);

    BaseModel.query(sql, function (results) {
        debug(results[0]);

        endConnection();

        deferred.resolve(results[0]);
    }, function () {
        deferred.reject();
    });

    return deferred.promise;
}

module.exports = new UserModel();

基础模型

var debug       = require('debug')('base.model'),
    connection;

function BaseModel () {}

BaseModel.prototype.setConnection   = setConnection;
BaseModel.prototype.query           = query;

function setConnection (con) {
    connection = con;
}

function query(sql, callback, errorCallback) {
    callback        = callback || undefined;
    errorCallback   = errorCallback || undefined;

    debug('query: ' + sql);

    connection.query(sql, function (error, results, fields) {
        if (error) {
            debug(error);

            if (errorCallback) {
                errorCallback();
            }

            return;
        }

        if (callback) {
            callback(results, fields);
        }
    });
}

module.exports = new BaseModel();

任何人对我做错了什么想法?

0 个答案:

没有答案