I see in the documentation that listeners will be executed "in order" for a given event, but what other guarantees are there? For instance, is the following code guranteed to print 0 through 9 sequentially, or is that just a side effect of the current implementation?
var EventEmitter = require('events').EventEmitter
var ev = new EventEmitter();
ev.on("foo", console.log);
for (var i = 0; i < 10; i++) {
ev.emit("foo", i);
}
Listeners will be executed in the order that they are attached.
var EventEmitter = require('events').EventEmitter
var ev = new EventEmitter();
ev.on("foo", console.log);
ev.on("foo", function(i){ console.log('...'); });
for (var i = 0; i < 10; i++) {
ev.emit('foo', i);
}
Will output:
1
...
2
...
3
...
// and so on
But change the order of registration to:
ev.on('foo', function(i) { console.log('...'); });
ev.on('foo', console.log);
And the output will be:
...
1
...
2
...
3
// and so on
As I'm sure you can tell, that has nothing to do with the fact that the original code prints the values sequentially. I'm not sure if listeners called via emit are executed on a separate thread or not but by the looks of your results, I'd guess not which is why you see the sequential output.
For instance, is the following code guaranteed to print 0 through 9 sequentially
Hmm. I don't think it's actually guaranteed in the documentation anywhere, but that's the only reasonable way an event queue can work. If events aren't delivered in the order that they were sent, it can lead to very tangled logic on the receiving end.
As pointed out in one of the comments on your question, in the all-JavaScript case, it can't work any other way, because the event is dispatched synchronously during the emit() call. For native objects, something similar applies - they need to call emit() via the V8 bindings, so ultimately those events get delivered in the order the native code sends them, as well.