Reputation: 2898
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(); }); };
Upvotes: 2
Views: 4420
Reputation: 106696
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);
});
});
}
Upvotes: 5