Node.JS:类方法作为回调

Node.JS: class method as callback

本文关键字:回调 类方法 JS Node      更新时间:2024-06-19

我在node.js中使用类,但在本例中,this.done是未定义的。关于如何轻松解决这个问题,有什么想法吗?我现在不想回到回调地狱或学习使用承诺。

MyClass.prototype.method1 = function(done) {
  this.method1Done = done;
  mysql.query([...], this._method1QueryCallback);
}
MyClass.prototype._method1QueryCallback = function(err, rows) {
  [...]
  this.done(err, rows)
}

在将某个特定的this上下文用作回调之前,您需要将其bind添加到方法中,否则调用者将提供自己的this(这可能不是您所期望的)。

最简单的方法是:

mysql.query([...], this._method1QueryCallback.bind(this))

假设您在调用mysql.query时知道this是正确的作用域。

这确实会使以后很难解除回调绑定,如果您正在设置事件处理程序,这可能会成为一个问题。在这种情况下,您可以执行以下操作:

this._method1QueryCallback = this._method1QueryCallback.bind(this);

在构造函数中的某个位置,或者在传递回调之前。