【发布时间】:2015-03-11 03:57:44
【问题描述】:
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_时,在exchangeReady_函数中有一个错误显示this.ex_是null。
我想在事件open和ready函数中如何添加Q?
【问题讨论】:
-
如果您愿意使用现代的 Promise 库,您可以摆脱答案中丑陋的
.binds。 (可能还有更好的性能) -
你能给我一些现代的 promise 库吗?
-
例如,Bluebird 是最快的,并且有能力处理这个问题。
标签: javascript node.js promise amqp q