简体   繁体   中英

Node.js npm mssql function returning undefined

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

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

  });

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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