我想在node.js XMPP客户端中使用promisify事件发射器,这是我的代码:
this.watiForEvent = function (eventEmiter, type) {
return new Promise(function (resolve) {
eventEmiter.on(type, resolve);
})
};
this._response = function () {
return this.watiForEvent(this.client, 'stanza');
};
在上面的代码中,我 promise 了 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);
});
我的问题是节事件只调用了一次。也许 promise 不好?
最佳答案
Es6-Promises 有 3 种状态,待定、已解决和已拒绝。
在您提供的代码中,eventEmitter正在多次解决 promise 。
eventEmiter.on(type, resolve);
那是行不通的,因为一旦 promise 被拒绝或解决,其状态就无法更改,您无法多次解决 promise 。 p>
我建议使用可观察模式:
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);
});
}
}
}
关于javascript - 将 Promise 与事件发射器一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33706410/