如何将 Promise 添加到 javascript 中的事件处理程序
How to add Promise to event handler in javascript
现在我想用承诺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_
null
在exchangeReady_
函数中。
我想如何在事件open
和ready
函数中添加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) );
代码中的其他几个位置也存在相同的问题。
相关文章:
- keyup事件处理程序更改焦点不适用于快速键入
- 提示使用服务器端事件处理程序激活JavaScript
- 将事件处理程序绑定到任何可能的事件
- 正在将事件处理程序添加到不存在的类
- 在循环中附加事件处理程序时出现浏览器性能问题
- 在同一个javascript事件处理程序中调用不同的函数
- 有没有一种方法可以让内联事件处理程序在元素创建后立即执行
- 检查事件处理程序参数
- 实现延迟的jquery更改事件处理程序
- 如何使用Node.js在JavaScript模块文件之间使用事件处理程序
- 如何使jQuery的“bind”或“on”事件处理程序幂等
- 带有参数的Javascript事件处理程序
- Jquery事件处理程序仅适用于匿名函数
- 如何从另一个处理程序内部取消JavaScript事件处理程序函数的执行
- 如何在jQuery事件处理程序中存储和重用超时
- 如何向onClick事件处理程序传递一个接受参数的函数,并且仍然将该函数绑定到组件's”;这个“;上下文
- 异步处理所有事件处理程序的方法
- jsplumb中的Click事件处理程序丢失“;这个“;对象
- 构造函数中的事件处理程序与构造函数外的事件处理函数的行为不同
- 如何在事件处理程序的回调中防止Default