Thursday, 26 April 2018

node.js - Nodejs with Mysql Database Return value



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

});

};

Answer



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


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...