如何在 javascript 中将 Promise 添加到事件处理程序

How to add Promise to event handler in javascript

现在我要包装amqp with Promise Q,这里是代码

Sender.prototype.createConnection_ = function () {
    var deferred = Q.defer();
    this.con_ = amqp.createConnection( this.connectOpt_, this.implementOpt_ );
    deferred.resolve( this.con_ );

    return deferred.promise;
}

Sender.prototype.connectionReady_ = function() {
    var deferred = Q.defer(),
      self = this;

    self.con_.on('ready', function() {
        console.log('connection is ok now');
        deferred.resolve(self.con_);
    });
    return deferred.promise;
}

Sender.prototype.createExchange_ = function() {
    var deferred = Q.defer(),
      self = this;

    this.con_.exchange( this.exchangeName_, this.exchangeOpt_, function ( ex ) {
        self.ex_ = ex;
        deferred.resolve(self.ex_);
    });
    return deferred.promise;
}

Sender.prototype.exchangeReady_ = function() {
    var deferred = Q.defer(),
      self = this;

    this.ex_.on('open', function() {
        console.log('Sender: exchange opened');
        deferred.resolve(this.ex_);
    });
    return deferred.promise;
}

Sender.prototype.connect_ = function() {
    var self = this;
    return self.createConnection_()
            .then( self.connectionReady_() )
            .then( self.createExchange_() )
            .then( self.exchangeReady_() )
            .catch( function(err) {
                console.info( err );
            });
}

当我想调用connect_时,有一个错误显示this.ex_exchangeReady_函数中是null

我想知道如何在事件 openready 函数中添加 Q

您正在立即调用您的函数,而不是将函数引用传递给 .then() 处理程序。 .then() 采用函数引用,而不是承诺作为参数。更改为:

Sender.prototype.connect_ = function() {
    return this.createConnection_()
            .then( this.connectionReady_.bind(this) )
            .then( this.createExchange_.bind(this) )
            .then( this.exchangeReady_.bind(this) )
            .catch( function(err) {
                console.info( err );
            });
}

.bind(this) 允许您传递函数引用(.then() 基础架构稍后可以调用的东西)并且仍然将其绑定到 this


当您像这样传递回调时,您似乎也可能遇到绑定问题:

amqp.createConnection( this.connectOpt_, this.implementOpt_ );

这些回调将不会绑定到 this。相反,在方法的任何回调上使用 .bind() 像这样:

amqp.createConnection( this.connectOpt_.bind(this), this.implementOpt_.bind(this) );

您的代码中的其他几个地方也存在同样的问题。