繁体   English   中英

从节点mssql返回数据执行函数

[英]returning data from node mssql execute functions

我正在使用npm的 mssql用于Node.js的Microsoft SQL Server客户端 )程序包。我正在尝试执行驻留在sql server数据库中的存储过程。我可以将其导出以在其他模块中使用。以下是我正在尝试做的事情。

function monthlyIceCreamSalesReport (scope){
var connObj = connConfig();
connObj.conn.connect(function(err){
    if(err){
        console.log(err);
        return;
    }
    connObj.req.input('Month',4);
    connObj.req.input('Year',2016);

    connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue){
        if(err){
            console.log(err);
        }
        else {
            console.log(recordsets[0]); // successfully receiving the value
        }
        connObj.conn.close();
    });
  });
  console.log('check for recordsets', recordsets[0]); // undefined
  return recordsets[0];
}
var sqlServerObj = {
    monICSalesReport : monthlyIceCreamSalesReport,
};
module.exports = sqlServerObj;

如代码片段所示,由于recordsets [0]的值未定义,因此导出此函数没有用。

您不能以异步方式以这种方式return 您可以通过传递callback函数来获取它

尝试提供这样的回调函数

function monthlyIceCreamSalesReport(scope, callback) { // pass a callback to get value

    var connObj = connConfig();
    connObj.conn.connect(function(err) {
        if (err) {
            console.log(err);
            return;
        }
        connObj.req.input('Month', 4);
        connObj.req.input('Year', 2016);

        connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue) {
            if (err) {
                console.log(err);
            } else {
                console.log(recordsets[0]);
                connObj.conn.close();
                return callback(null, recordsets[0]); //return as a callback here and get that value in callback from where you called this function 
            }
        });
    });
 }
var sqlServerObj = {
    monICSalesReport: monthlyIceCreamSalesReport,
};
module.exports = sqlServerObj;

注意:请参阅评论以了解更改

recordsets[0]未定义,因为仅在connObj.req.execute函数范围内定义。 您可以通过以下方式执行此操作:

function monthlyIceCreamSalesReport (scope, cb){
 var connObj = connConfig();
 connObj.conn.connect(function(err){
   if(err){
      console.log(err);
      return cb(Error("Something wrong"));
  }
  connObj.req.input('Month',4);
  connObj.req.input('Year',2016);

connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue){
    if(err){
        console.log(err);
        connObj.conn.close();
        return cb(Error("Something wrong"));
    }
    else {
        console.log(recordsets[0]); // successfully receiving the value

        connObj.conn.close();
        return cb(recordsets[0]);
    }
  });
});

}

var sqlServerObj = {
   monICSalesReport : monthlyIceCreamSalesReport,
};

module.exports = sqlServerObj;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM