具有Mysql数据库的Nodejs返回值
我有以下代码。 我对nodejs&js比较陌生
我想在1.日志中获取值,但我得到了undefined。 只有2.日志输出到日志。
我从callback和https://github.com/felixge/node-mysql读取nodeJS返回值,但是没有关于返回值的示例。
我不知道如何使用node-mysql页面中的给定示例的return语句。
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){ 如果(犯错)抛出犯错; var response = {}; connection.query(“select * from external_geo_units where geo_unit_id =”+ id,function(err,rows){ 如果(犯错)抛出犯错; response.data = rows; // 2. log 的console.log(响应); 回复回复; }); connection.release(); }); };
它是asynchronous的,所以你必须传入一个callback才能获得准备好的值。 例:
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); }); }); }