在Node.js中使用setImmediate()和process.nextTick()的意义

时间:2015-03-03 11:27:07

标签: javascript node.js

我正在学习Node.js并且很难理解setImmediate()和process.nextTick()的工作。为了理解清楚的概念,我有三个程序,一个是简单的node.js程序,一个是使用setImmediate(),另一个是使用process.nextTick()。显然,这三个人都以不同的方式表现。如果有人解释这些程序在操作过程中的不同之处并解释使用这两个计时器进行有效的Node.js编程的重要性,将会有很大的帮助。

计划1 :(没有setImmediate()和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();

结果:

Saw a Aston Martin
Saw a Lamborghini
Saw a Bugatti
Saw a Porsche
Saw a Ferrari
entered file operation
file exists

计划1 :(使用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();

结果:

Saw a Aston Martin
entered file operation
Saw a Lamborghini
file exists
Saw a Bugatti
Saw a Porsche
Saw a Ferrari

计划2 :(使用prcess.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();

结果:

Saw a Aston Martin
entered file operation
Saw a Lamborghini
Saw a Bugatti
Saw a Porsche
Saw a Ferrari
file exists

1 个答案:

答案 0 :(得分:4)

使用 process.nextTick()延迟回调在之前运行任何其他I / O事件。
使用 setImmediate(),执行将排队队列中已有的任何I / O事件。