2

I have the following code. I am relative new to nodejs &js

I want to get values in 1. log but i get undefined. Only 2. log is outputed to the log.

I read nodeJS return value from callback and https://github.com/felixge/node-mysql but there is no example about return value.

I donot know how to use return statement with the given example in node-mysql page.

exports.location_internal = function (req, res) {
    var r = getExternalLocation(2);
        // 1. log  
    console.log(r);
    res.send( r);
}

var getExternalLocation = function (id) {
    pool.getConnection(function(err, connection){
      if(err) throw err;

      var response = {};
      connection.query( "select * from external_geo_units where geo_unit_id = "+id,  function(err, rows){
        if(err) throw err;
        response.data= rows;
                // 2. log
        console.log(response);
        return  response;
      });
      connection.release();
    });

};

1 Answer 1

5

It's asynchronous, so you have to pass in a callback to get the value when it's ready. Example:

exports.location_internal = function(req, res, next) {
  getExternalLocation(2, function(err, rows) {
    if (err)
      return next(err);
    console.log(rows);
    res.send(rows);
  });
};

function getExternalLocation(id, cb) {
  pool.getConnection(function(err, conn) {
    if (err)
      return cb(err);

    conn.query("select * from external_geo_units where geo_unit_id = ?",
               [id],
               function(err, rows) {
      conn.release();
      cb(err, rows);
    });
  });
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.