Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/415.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript NodeJS等待mySQL查询完成_Javascript_Mysql_Node.js_Express_Asynchronous - Fatal编程技术网

Javascript NodeJS等待mySQL查询完成

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,

我试图将对象从控制器传递到视图。因为我想将我的查询与控制器分开,所以我正在加载一个JS对象(模型)

我的模型如下所示:

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
。谢谢!这对我来说是一个巨大的错误。我现在更新答案。