What are the proper use cases for process.nextTick in Node.js?

Solution 1:

process.nextTick puts a callback into a queue. Every callback in this queue will get executed at the very beginning of the next tick of the event loop. It's basically used as a way to clear your call stack. When the documentation says it's like setTimeout, it means to say it's like using setTimeout(function() { ... }, 1) in the browser. It has the same use cases.

One example use case would be, you create a constructor for some object that needs events bound to it. However, you can't start emitting events right away, because the code instantiating it hasn't had time to bind to events yet. Your constructor call is above them in the call stack, and if you continue to do synchronous things, it will stay that way. In this case, you could use a process.nextTick before proceeding to whatever you were about to do. It guarantees that the person using your constructor will have time enough to bind events.

Example:

var MyConstructor = function() {
  ...
  process.nextTick(function() {
    self._continue();
  });
};

MyConstructor.prototype.__proto__ = EventEmitter.prototype;

MyConstructor.prototype._continue = function() {
  // without the process.nextTick
  // these events would be emitted immediately
  // with no listeners. they would be lost.
  this.emit('data', 'hello');
  this.emit('data', 'world');
  this.emit('end');
};

Example Middleware using this constructor

function(req, res, next) {
  var c = new MyConstructor(...);
  c.on('data', function(data) {
    console.log(data);
  });
  c.on('end', next);
}

Solution 2:

It simply runs your function at the end of the current operation before the next I/O callbacks. Per documentation you can use it run your code after the callers synchronous code has executed, potentially if you can use this to give your API/library user an opportunity to register event handlers which need to be emitted ASAP. Another use case is to ensure that you always call the callbacks with asynchronously to have consistent behaviours in different cases.

In the past process.nextTick would be have been used provide an opportunities for I/O events to be executed however this is not the behaviour anymore and setImmediate was instead created for that behaviour. I explained a use case in the answer of this question.