Given some EventEmitter instance in Node.js, is it absolutely guaranteed that all events will be handled in the same order as they appear in the code?
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var Emitter = function () {
EventEmitter.call(this);
var that = this;
this.test = function () {
that.emit('eventA');
that.emit('eventB');
}
};
inherits(Emitter, EventEmitter);
var emitter = new Emitter();
emitter.on('eventA', function () {
doTaskA();
});
emitter.on('eventB', function () {
doTaskB();
});
emitter.test();
Can there appear a situation where doTaskB() will start before doTaskA()?
Yes, all events will be handled in the same order as they appear in the code. Event is fired immediately after the emit call. You can see it in EventEmmiter.emit source code. But binding your application logic to the order of events does not the best way.