0

Hi i am trying to use two selects in one JS file in node js and sql server. I am unable to figure out the syntax for this. I need a select to get all the persons from a table and another select to count the total number of persons in that table.Will it be possible to put those two selects in a single JS file. If so can someone help me with the syntax?

Here is the code i tried and i am getting the error "cant Set headers after they are sent"

var sql = require("mssql"); var dbConfig = {

server: "XXXXX",
database: "XXXXX",
user: "XXXXX",
password: "XXXX",
port: 1433

}; exports.list = function(req, res){

sql.connect(dbConfig, function (err) {

    if (err) console.log(err);

    var request = new sql.Request();

    request.query('select * from PERSON', function (err, recordset) {

        if (err) 
            console.log(err)
        else
           console.log(recordset)
            res.render('personinfo_itwx', { data: recordset });

    });

        request.query('select count(*) from PERSON', function (err, recordset) {

        if (err) 
            console.log(err)
        else
           console.log(recordset1)
            res.render('personinfo_itwx', { data: recordset1 });

});









});

};

  • can't you simply make two async requests? For instance, with async library. https://github.com/caolan/async – Patryk Cieszkowski Feb 22 '17 at 23:14
  • Hi Patryk, Can you help me with the Syntax of using async please? i am new to node.js so never got to use async. –  Feb 23 '17 at 14:59

1 Answers1

0

@Aditya I'm not sure it's the best way to do so, although I would simply make two different requests, in order to achieve what you need. As I mentioned my in my comment, easiest way, would be to use (for instance) async library. And here's example you've asked for.

WARNING: I did not look at mysql docs

const async = require('async')

// {
  async.series([
    function(next)
    {
      new sql.Request()
        .query('SELECT * from PERSON', next(err, resultList))
    },
    function(next)
    {
      new sql.Request()
        .query('SELECT COUNT(*) from PERSON', next(err, count))
    }
  ], (err, result) =>  
  {
    /* 
      err: String
        - if any of the shown above return an error - whole chain will be canceled.

      result: Array
        - if both requests will be succesfull - you'll end up with an array of results 

      --- 

      Now you can render both results to your template at once

    */
  })
// }

Surely, if you want manipulate with errors or results once you get them - you always may push error and results to new function, play with your data, and return the callback afterwards. Like so:

function(next)
{
  new sql.Request()
    .query('SELECT * from PERSON', (err, resultList) =>
    {
      if (err)
      {
        return next(err, null)            
      }

      /*
        data manipulation
      */

      return next(null, resultList)
    })
},