Reputation: 167
I am learning Node.js and having a very hard time in understanding the working of setImmediate()
and process.nextTick()
. In order to understand the concepts clear, I have three programs, one plain, simple node.js program, one using setImmediate()
and one using process.nextTick()
. Apparently all three behaving in different way. It would be of great help if anyone explain how these programs differ in operation under the hood and explain the significance of using both timers for effective Node.js programming.
Program 1: (without setImmediate()
and process.nextTick()
)
var fs = require('fs');
function logCar(car, callback){
console.log("Saw a %s", car);
if(cars.length){
callback();
}
}
function logCars(cars){
var car = cars.pop();
logCar(car, function(){
logCars(cars);
});
}
var cars = ["Ferrari", "Porsche", "Bugatti",
"Lamborghini", "Aston Martin"];
logCars(cars);
var fileCheck = function(){
console.log('entered file operation');
fs.stat("fileio.js", function(err,stats){
if(stats)
console.log("file exists");
});
}
fileCheck();
Result:
Saw a Aston Martin
Saw a Lamborghini
Saw a Bugatti
Saw a Porsche
Saw a Ferrari
entered file operation
file exists
Program 1: (with setImmediate()
)
var fs = require('fs');
function logCar(car, callback){
console.log("Saw a %s", car);
if(cars.length){
setImmediate(function(){
callback();
});
}
}
function logCars(cars){
var car = cars.pop();
logCar(car, function(){
logCars(cars);
});
}
var cars = ["Ferrari", "Porsche", "Bugatti",
"Lamborghini", "Aston Martin"];
logCars(cars);
var fileCheck = function(){
console.log('entered file operation');
fs.stat("fileio.js", function(err,stats){
if(stats)
console.log("file exists");
});
}
fileCheck();
Result:
Saw a Aston Martin
entered file operation
Saw a Lamborghini
file exists
Saw a Bugatti
Saw a Porsche
Saw a Ferrari
Program 2: (with process.nextTick()
)
var fs = require('fs');
function logCar(car, callback){
console.log("Saw a %s", car);
if(cars.length){
process.nextTick(function(){
callback();
});
}
}
function logCars(cars){
var car = cars.pop();
logCar(car, function(){
logCars(cars);
});
}
var cars = ["Ferrari", "Porsche", "Bugatti",
"Lamborghini", "Aston Martin"];
logCars(cars);
var fileCheck = function(){
console.log('entered file operation');
fs.stat("fileio.js", function(err,stats){
if(stats)
console.log("file exists");
});
}
fileCheck();
Result:
Saw a Aston Martin
entered file operation
Saw a Lamborghini
Saw a Bugatti
Saw a Porsche
Saw a Ferrari
file exists
Upvotes: 0
Views: 415
Reputation: 122
Callbacks deferred with process.nextTick()
run before any other I/O event is fired.
With setImmediate()
, the execution is queued behind any I/O event that is already in the queue.
Upvotes: 4