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_
函数中有一个错误显示null
为exchangeReady_
。
我想如何在事件Q
和open
功能中添加ready
?
答案 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) );
您的代码中存在同样的问题。