How to add Promise to event handler in javascript

时光毁灭记忆、已成空白 提交于 2019-12-12 03:07:49

问题


Now I want to wrap amqp with Promise Q, here are the codes

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

When I want to invoke connect_, there is one error show that this.ex_ is null in the exchangeReady_ function.

I want to how to add Q in the event open and ready function ?


回答1:


You're calling your functions immediately, rather than passing a function reference to the .then() handlers. .then() takes a function reference, not a promise as an argument. Change to this:

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

The .bind(this) lets you pass a function reference (something the .then() infrastructure can call later) and still have it bound to this.


It looks like you may also have binding issues when you pass callbacks like this:

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

These callbacks will not stay bound to this. Instead, use .bind() like this on any callback that is method:

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

The same issue exists several other places in your code.



来源:https://stackoverflow.com/questions/28956946/how-to-add-promise-to-event-handler-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!