Chris Rutherford
Chris Rutherford

Reputation: 1672

NodeJS MSSQL driver Passing data to a calling function

Working with an SQL Server in NodeJS, and I have confirmed that it's pulling the data, but I'm trying to pass the data back to a calling function.

Here's my call to the function that queries the database:

const dbq = require('./dbquery.js');
app.get('/:id', (req, res) => {
  reqlog(`/${req.params.id}`);
  var set = dbq.getPersonById(req.params.id);
  console.log(set);
});

and here is the function inside dbquery.js:

qry.getPersonById = (id) => {

  mssql.connect(sqlConfig).then(() => {
    new mssql.Request().query(`select * from FNVPeople where IndivID=${id}`).then((record)=>{
      console.log(record);
      return record;
    }).catch((err)=>{
      console.log(err);
    });
  });
}

Should my call to the function look like this?

var dataset = await(dbq.getPersonById(req.params.id));

Upvotes: 0

Views: 130

Answers (2)

Wiktor Zychla
Wiktor Zychla

Reputation: 48279

You should return the promise to the client to deal with (note two additional returns):

qry.getPersonById = (id) => {

  return mssql.connect(sqlConfig).then(() => {
    return new mssql.Request().query(`...`)
       .then((record)=>{
          console.log(record);
          return record;
       })
       .catch((err)=>{
          console.log(err);
       });
  });

}

Then, the client deals with the promise

app.get('/:id', (req, res) => {
  reqlog(`/${req.params.id}`);
  dbq.getPersonById(req.params.id).then( set =>
     console.log(set); 
  );
});

By rewriting promises to async/await you could even have

qry.getPersonById = async (id) => {

  try {
     await mssql.connect(sqlConfig)
     var record = await new mssql.Request().query(`...`);
     console.log(record);
     return record;
  }
  catch (err) {
     console.log(err);
  }
}

and

app.get('/:id', async (req, res) => {
  reqlog(`/${req.params.id}`);
  var set = await dbq.getPersonById(req.params.id);
  console.log(set); 
});

Upvotes: 0

Subburaj
Subburaj

Reputation: 5192

Because of Async nature.

Try for the following:

const dbq = require('./dbquery.js');
app.get('/:id', (req, res) => {
  reqlog(`/${req.params.id}`);
  dbq.getPersonById(req.params.id, function(err, res){
      console.log(res);
  });      
});


qry.getPersonById = (id, callback) => { 

    mssql.connect(sqlConfig).then(() => {
        new mssql.Request().query(`select * from FNVPeople where IndivID=${id}`).then((record)=>{
          console.log(record);
          callback(null, record);
        }).catch((err)=>{
          console.log(err);
        });
      });
    }

Upvotes: 1

Related Questions