简体   繁体   English

Node.js NPM MSSQL函数返回未定义

[英]Node.js npm mssql function returning undefined

I am using mssql with node.js to connect to an sql server db. 我将MSSQL与node.js一起使用以连接到SQL Server数据库。 I am trying to reduce code by wrapping the connection code in a function with one query parameter. 我试图通过将连接代码包装在具有一个查询参数的函数中来减少代码。 When I call the function from with in a router.get function, it returns undefined. 当我从router.get函数中的with调用函数时,它返回未定义。

Any help would be much appreciated. 任何帮助将非常感激。

 function sqlCall(query) { var connection = new sql.Connection(config, function(err) { if (err) { console.log("error1"); return; } var request = new sql.Request(connection); // or: var request = connection.request(); request.query(query, function(err, recordset) { if (err) { console.log("error2"); return; } return (recordset); }); }); } 

router code 路由器代码

 router.get('/', function(req, res) { var queryString = "select * from ....."; res.json(sqlCall(queryString)); //sqlCall(queryString) }); 

You are trying to treat the sqlCall as a synchronous function with a return value, while the request.query function on the opposite is an asynchronous function, expecting a callback. 您正在尝试将sqlCall视为具有返回值的同步函数,而相反的request.query函数是异步函数,需要回调。

Since Node.js uses non blocking IO and callback structures for flow control, using an asynchronous structure based around callbacks is the way to go. 由于Node.js使用非阻塞IO和回调结构进行流控制,因此使用基于回调的异步结构是可行的方法。 In your case this could look like this: 在您的情况下,可能看起来像这样:

router.get('/', function(req, res) {


  var queryString = "selec * from .....";
  sqlCall(queryString, function(err, data) {
     if (typeof err !== "undefined" && err !== null) {
       res.status(500).send({
         error: err
       });
       return;
     }

     res.json(data);
  });
});

with your other component looking like this: 其他组件如下所示:

function sqlCall(query, cb) {
  var connection = new sql.Connection(config, function(err) {
    if (typeof err !== "undefined" && err !== null) {
      cb( err );
      return
    }

    var request = new sql.Request(connection); // or: var request = connection.request();
    request.query(query, function(err, recordset) {
      cb( err, recordset );
    });

  });

}

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

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