Ошибка подключения в модуле узла mssql

Я использую модуль узла mssql в своем проекте. Все хорошо до тех пор, пока я не делаю никаких асинхронных вызовов.

При многократном асинхронном вызове его запуск дает мне ошибку соединения «Соединение закрыто». может кто-нибудь заглянуть в код и помочь мне.

==== SqlServerDAL.js что-то вроде этого

 var sql = require('mssql');
 var _sqlConfig = require("../../../../config/dbconfig.json");

function SqlServerDAL() {
    this._sqlConfig = _sqlConfig;
    this._sqlConnection = null;
}

/**
 * @param : request > request or query parmanter to excute sql query
 * @param : callback > after execution neect to send response back to serr  
 * @param : sqlReqConf > to build the requst object from the configuration
 */
SqlServerDAL.prototype.executeRequest = function (request, callback) {

    var self = this;

    self._sqlConnection = new sql.Connection(this._sqlConfig);

    this._sqlConnection.connect().then(function () {

        var _sqlRequest = new sql.Request(self._sqlConnection);

        try {
            _sqlRequest.input('someVar','someValue')

            _sqlRequest.execute('myStoreProc').then(function (recordsets) {
                callback(null, recordsets);
            }).catch(function (sqlEx) {
                callback({
                    code: "ERR0003",
                    message: sqlEx.message,
                    type: sqlEx.name
                }, null);
            });
        } catch (sqlEx) {
            callback({
                code: "ERR0004",
                message: sqlEx.message,
                type: sqlEx.name
            }, null);
        }

    }).catch(function (sqlEx) {
        callback({
            code: "ERR0001",
            message: sqlEx.message,
            type: sqlEx.name
        }, null);
    });
};

module.exports = new SqlServerDAL();

этот файл выше, который я вызываю из dal.js

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global require, module,logger */

    var Q = require("q");
    var sqlServerDAL = require('./sqlDAL/sqlServerDAL');

    /**
     * 
     * @constructor:  
     */

    function DAL() {}

    /**
     * @param : customRequst : this json object will come from respective dbschema files,
     *                       This object bening used to build sqlRequest object
     */

    DAL.prototype.executeRequest = function (customRequest) {

        var deferred = Q.defer();

        sqlServerDAL.executeRequest(customRequst, function (sqlEx, recordsets) {

            if (recordsets) {
                logger.info("_sqlRequest is successfully executed:" + JSON.stringify(recordsets));
                deferred.resolve(recordsets);
            } else if (sqlEx) {
                deferred.reject({
                    code: sqlEx.code,
                    message: sqlEx.message,
                    type: sqlEx.name
                });
            }
        });

        return deferred.promise;
    };


    module.exports = new DAL();

// мой контроллер похож

 app.use("mycontroller", function(req, res, next){
 var dal = new Dal();
 dal.executRequest(function(result){
     res.send(result)
 } , function(err){
   console.log("got some error" + errr)
 })
  })

person Ashish Yadav    schedule 12.04.2016    source источник
comment
У меня была такая же проблема с конфигурацией json. Пробовал устаревшую строку подключения, сработало. Попробуйте mssql://${cfg.db.user}:${cfg.db.password}@${cfg.db.server}/SQLEXPRESS/${cfg.db.database}   -  person Swaraj Giri    schedule 12.04.2016


Ответы (1)


Да, я получил ответ. Из-за асинхронного вызова новый запрос (self.connection) получает старый объект, который закрывается старым вызовом функции. Итак, ответ: нам нужно создать новый запрос, подобный этому.

this._sqlConnection.connect().then(function (connection ) {
  var _sqlRequest = new sql.Request(connection);
})
person Ashish Yadav    schedule 12.04.2016