[英]Using promises with event emitters
I want promisify event emitter in an node.js XMPP client, this is my code: 我想要在node.js XMPP客户端中实现事件发射器,这是我的代码:
this.watiForEvent = function (eventEmiter, type) {
return new Promise(function (resolve) {
eventEmiter.on(type, resolve);
})
};
this._response = function () {
return this.watiForEvent(this.client, 'stanza');
};
in above code I promisify the XMPP stanza event emitter and use it something like this 在上面的代码中,我承诺了XMPP节事件发射器,并使用了类似的东西
CcsClient.prototype.responseHandler = function () {
var _this = this;
return _this._response().then(function (stanza) {
_this.responseLimit--;
if (stanza.is('message') && stanza.attrs.type !== 'error') {
var messageData = JSON.parse(stanza.getChildText("gcm"));
switch (messageData.message_type) {
case 'control':
if (messageData.control_type === 'CONNECTION_DRAINING') {
_this.draining = true;
}
return;
case 'ack':
return {
messageId: messageData.message_id,
from: messageData.from
};
gcm.responseHandler().then(function (options) {
console.log(options);
}).
catch (function (error) {
console.log(error);
});
My problem is stanza event just called one time. 我的问题是节事件仅被调用一次。 Maybe promise is not good?
也许诺言不好?
Es6-Promises have 3 states, pending , resolved and rejected . Es6-Promise具有3个状态,即未决 ,已解决和已拒绝 。
In the code you provided eventEmitter is resolving the promise multiple times . 在您提供的代码中, eventEmitter 多次解决了promise。
eventEmiter.on(type, resolve);
Thats is not going to work, because once a promise is rejected or resolved its state can not be changed, you can not resolve a promise multiple times . 那是行不通的,因为一旦承诺被拒绝或解决,其状态就无法更改,那么您将无法多次解决承诺。
I suggest using the observable pattern : 我建议使用可观察的模式 :
function observable(){
var cbs = { }; // callbacks;
return {
on: function(type,cb) {
cbs[type] = cbs[type] || [];
cbs[type].push(cb);
},
fire: function(type){
var arr = cbs[type] || [];
var args = [].slice.call(arguments,1);
arr.forEach(function(cb){
cb.apply(this,args);
});
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.