Javascript NodeJS等待mySQL查询完成
我试图将对象从控制器传递到视图。因为我想将我的查询与控制器分开,所以我正在加载一个JS对象(模型) 我的模型如下所示:Javascript NodeJS等待mySQL查询完成,javascript,mysql,node.js,express,asynchronous,Javascript,Mysql,Node.js,Express,Asynchronous,我试图将对象从控制器传递到视图。因为我想将我的查询与控制器分开,所以我正在加载一个JS对象(模型) 我的模型如下所示: function MyDatabase(req) { this._request = req; this._connection = null; this.init(); }; MyDatabase.prototype = { init: function() { this._request.getConnection( function(err,
function MyDatabase(req) {
this._request = req;
this._connection = null;
this.init();
};
MyDatabase.prototype = {
init: function() {
this._request.getConnection( function(err, con) {
if(err) return false;
return this._connection = con;
}.bind(this));
},
getFromTable: function(table) {
this._connection.query('SELECT * FROM '+ table +';', function(err, result) {
if(err)
return false;
else if( !result )
return {error: 'Error bij het ophalen van foto\'s'};
else
return result;
}.bind(this));
}
};
module.exports = MyDatabase;
但是我不知道如何等到这个查询在我的控制器中完成。我已经找到了这个模块,并尝试了瀑布和并行等多种功能,但它们都不适用于我(或者我没有按照预期使用它)
我的控制器当前看起来如下所示:
var myDatabase = require('../dbmodel');
router.get('/', function(req, res, next) {
var db = new myDatabase(req);
async.waterfall([
function(callback) {
var db = new myDatabase(req);
var photos = db.getFromTable('photos');
callback(null, photos);
}
], function(p) {
res.locals.photos = p;
res.render('photos');
} );
});
我做错了什么?我知道NodeJS是异步工作的,不会等待任何函数完成。但一定有办法做到这一点。我做错了什么,或者我误解了什么
提前感谢!;) getFromTable方法应该接受一个回调,该回调将处理其执行的结果
// Accept a callback as a parameter
getFromTable: function(table, callback) {
this._connection.query('SELECT * FROM '+ table +';', function(err, result) {
if(err)
// execute the callback for a null result and an error.
callback(err, null);
else if( !result )
callback(new Error('Error bij het ophalen van foto\'s'),null);
else
// execute the callback on the result
callback(null, result);
}.bind(this));
}
现在可以通过以下方式使用该方法:
// This is the callback to be passed into the method.
function processResult(err, result) {
console.log(result);
}
db.getFromTable('photos', processResult);
太棒了,谢谢!一个小小的旁注:在else语句中,您将
null
作为第一个参数传递。在processResult()
中记录result
时,它返回null
,因为第二个参数包含result
。谢谢!这对我来说是一个巨大的错误。我现在更新答案。