primus / eventemitter3

EventEmitter3 - Because there's also a number 2. And we're faster.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Consider to execute event listeners async?

yuanhongboo opened this issue · comments

Wondering why not execute event listeners async?In some scene, it may block the main process.

eventemitter3/index.js

Lines 166 to 216 in 3f61c9f

EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
var evt = prefix ? prefix + event : event;
if (!this._events[evt]) return false;
var listeners = this._events[evt]
, len = arguments.length
, args
, i;
if (listeners.fn) {
if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
switch (len) {
case 1: return listeners.fn.call(listeners.context), true;
case 2: return listeners.fn.call(listeners.context, a1), true;
case 3: return listeners.fn.call(listeners.context, a1, a2), true;
case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
}
for (i = 1, args = new Array(len -1); i < len; i++) {
args[i - 1] = arguments[i];
}
listeners.fn.apply(listeners.context, args);
} else {
var length = listeners.length
, j;
for (i = 0; i < length; i++) {
if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
switch (len) {
case 1: listeners[i].fn.call(listeners[i].context); break;
case 2: listeners[i].fn.call(listeners[i].context, a1); break;
case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
default:
if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
args[j - 1] = arguments[j];
}
listeners[i].fn.apply(listeners[i].context, args);
}
}
}
return true;
};

Wondering why not execute event listeners async?In some scene, it may block the main process.

That is ok, it is not common to add a lot of listeners for the same event and it is not a computationally intensive task unless the listeners handle the event with a synchronous computationally intensive task themself. Also the EventEmitter is designed to work synchronously. When an event is emitted, registered listeners should be called immediately, you don't want other things to happen before the event is handled. For example, think about an error event. If the listener is called asynchronously, the error context might have already changed.