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

时间:2015-03-10 05:48:23

标签: javascript node.js promise amqp q

现在我想用amqp包裹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_函数中有一个错误显示nullexchangeReady_

我想如何在事件Qopen功能中添加ready

1 个答案:

答案 0 :(得分:1)

您立即调用函数,而不是将函数引用传递给.then()处理程序。 .then()接受函数引用,而不是作为参数的promise。改为:

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) );

您的代码中存在同样的问题。