Search code examples
node.jseventemitter

Is emitting events with process.nextTick preferred over emitting them inline?


There is a lot of emitting and listening for events in node.js.

I'm trying to decide if I should emit events inline and then return from a function or if I should generally use process.nextTick to emit events causing them to run later.

Which is the right (best) way to do this generally?

Someone told me that node.js's built in modules mostly use process.nextTick.


Solution

  • Generally in node v0.10 and newer you should use setImmediate. I cover all the various options in my blog post setTimeout and friends. The main point to note with event emitters is you need to allow the caller at least one tick to bind their event listeners before you start emitting events. This pattern is normally considered OK and should be supported:

    var myThing = new Thing();
    //if myThing immediately emits events,
    // they will be missed because they aren't bound yet
    myThing.on('event', handleEvent);
    //If events are delayed at least one tick, all is well,
    // the listener is bound and all events are handled
    

    For node earlier that v0.10, process.nextTick should be used.

    Note that if your emitter's logic requires async calls naturally (because it does I/O), you don't need setImmediate as doing the I/O already allows the event loop to complete the tick. You only need setImmediate in cases where you sometimes need to do I/O but in this case you don't need it, for example, you have a cached result from previous I/O.