在节点中,在发出消息后立即重置变量的最佳方法是什么

时间:2017-11-02 23:37:39

标签: node.js eventemitter

我目前正在使用ES6课程。我有一个场景,其中一个发出消息,在实例变量中发送值,然后我需要在发出后重置变量。

所以它看起来像下面这样(并按预期工作,但寻找更合适的方式):

// in class Ace
this.emit('someEvent', this.storage, () => {
    this.storage = {};
});

// in class Bay
// Assuming `this.instanceAce` is an instance of class Ace
this.instanceAce.on('someEvent', (data, cb) => {
    // do stuff with data
    cb();
}

这有效,但是为事件监听器提供回调的想法很奇怪。这假设我只有一个这个事件的监听器(当前是真的),但是在我可能有多个监听器的情况下会发生什么?

这个解决方案有更好的替代方案吗?有些东西似乎没有忽略事件模型的目的吗?

1 个答案:

答案 0 :(得分:1)

目前尚不清楚您正在尝试做什么,但如果您只想在任何听众可能从this.storage收到消息之前清除.emit()避免任何竞争条件,那么你可以这样做:

// Send storage and re-initialize the storage once we've captured it for sending
let temp = this.storage;
this.storage = {};
this.emit('someEvent', temp);

注意:常规EventEmitter对象不支持您正在使用的回调。有一些EventEmitter扩展支持该模型,但不支持基础EventEmitter对象,因为您可以看到here in the doc。如果我们知道您正在使用哪个确切的对象(显然支持这样的回调),我们可能会帮助您更好。