0

Still new to nodejs not sure what i am doing wrong here, i am trying to return a value from this function. However the variable i am trying to return outhjk is always reset.

function executeQuery( stmt, data ) {
  var outhjk = "";
  pool.connect(function(err, client, done) {
    if(err) {
      console.error('error fetching client from pool', err);
    }
    client.query(stmt, data, function(err, result) {
      //call `done()` to release the client back to the pool
      done();

      if(err) {
        return console.error('error running query', err);
      }
      outhjk = "just work please";
    });
  });
  return outhjk;
}
  • pool.connect will take little time and and last line will be returned before its execution due to async nature. – Amit Garg Aug 08 '16 at 04:17

2 Answers2

0

your query is not operating inside pool.connect its directly returning var = ""; if you are using latest version of node.js you can use new Promise((resolve, reject)=>{}); or if older version use 'async' module or any other module to handle node.js asynchronous functions

0

client.query is asynchronous. The return statement : return outhjk; will be called before the function executes because return is faster...

The standard way to deal with this is to use a callback function :

function executeQuery( stmt, data, callback ) {
  var outhjk = "";
  pool.connect(function(err, client, done) {
    if(err) {
      console.error('error fetching client from pool', err);
    }
    client.query(stmt, data, function(err, result) {
      //call `done()` to release the client back to the pool
      done();

      if(err) {
        return console.error('error running query', err);
      }
      outhjk = "just work please";
      callback(outhjk);
    });
  });
}

Then to call the function with a callback, you would do something like that :

var stmt = //stmt value here;
var data = //data value here;
executeQuery( stmt, data, function (outhjk) {
   //here you can use outhjk
});

Read this to learn the gist off callbacks

Community
  • 1
  • 1
AlexB
  • 3,518
  • 4
  • 29
  • 46