a blog for those who code

Thursday 9 April 2015

Usage of process.nexTick in NodeJS

In this post we are going to discuss about process.nextTick() function in NodeJS. Main usage of process.nextTick() is to defer the execution of an action till the next pass around the event loop. In simple terms it only means that once the current execution of the event loop is finished it calls up the callback function.

According to the above definition, any code written within the process.nextTick will execute in the next event loop before doing any I/O bound work.

Lets take an example,

function a() {
      console.log('Inside Function');
}
process.nextTick(a);
console.log('Outside Function');

The output of the above example is : 


Now you might say that this can be done using the simple setTimeout() function as well. But before making any judgement just have a look at these results below, nextTick() is far more efficient than setTimeout().


Lets take another example,

function calledFunction(yourName, callback) {
    process.nextTick(function () {
return callback('CodingDefined');
    });
}

function callingFunction() {
    console.log('Inside callingFunction');
    calledFunction('a', function(content) {
console.log('Welcome ' +content);
    });
    console.log('Going out of callingFunction');
}

callingFunction();

Output :

For more information have a look at NodeJS Docs .

Please Like and Share the Blog, if you find it interesting and helpful.

1 comment: