简体   繁体   English

node.js处理未设置的错误事件

[英]node.js handling unset error event

I'm working on a module that emits events, one of which is an 'error' event. 我正在处理一个发出事件的模块,其中一个是“错误”事件。

For example: 例如:

function A() {}

function A.prototype.start() {
 var error = true;
 if (error) {
  this.emit('error', error);
 }
 return this;
}

var a = new A()
a.on('error', function(err) {})

What happens is that even though I'm listening to the error event, the event is emitted, I guess before the listener is registered or the return of this . 发生的事情是,即使我正在侦听错误事件,也会发出该事件,我想应该在侦听器注册或this的返回之前。 What I've done is wrapped the emit in a setImmediate , such as: 我所做的是将发射包装在setImmediate ,例如:

function A.prototype.start() {
 var error = true;
 if (error) {
  setImmediate(function() {
   this.emit('error', error);
  });
 }
 return this;
}

As a general practice, is this fine? 作为一般惯例,这可以吗? or would there be a better way that's recommended for handling this and similar situations. 还是建议使用更好的方法来处理这种情况和类似情况。

It's good solution. 这是很好的解决方案。

EventEmitter events are pure-JS and don't get scheduled on the event loop; EventEmitter事件是纯JS的,不会在事件循环中安排; they are delivered synchronously. 它们是同步交付的。

In your situation, you emit an event before there's a listener, because you add a listener only after the event has been emitted. 在您的情况下,您在没有侦听器之前发出事件,因为仅在发出事件之后才添加侦听器。 If you "wait" for the next round of the event loop, by using setImmediate() , you basically postpone emitting the event until a time when the listener has been added. 如果“等待”事件循环的下一轮,则使用setImmediate() ,基本上可以将事件的发出推迟到添加侦听器之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM