Node.js npm mssql function returning undefined

可紊 提交于 2019-12-12 20:09:06

问题


I am using mssql with node.js to connect to an sql server db. 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.

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)

});

回答1:


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.

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. 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 );
    });

  });

}


来源:https://stackoverflow.com/questions/28041975/node-js-npm-mssql-function-returning-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!