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

How to add Promise to event handler in javascript

本文关键字:事件处理 程序 javascript Promise 添加      更新时间:2023-09-26

现在我想用承诺Q包装amqp,这是代码

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_ nullexchangeReady_函数中。

我想如何在事件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) );

代码中的其他几个位置也存在相同的问题。