gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:09:17 26 4
gpt4 key购买 nike

我正在学习 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:(使用 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();

结果:

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

最佳答案

使用 process.nextTick() 延迟的回调在触发任何其他 I/O 事件之前运行。

使用setImmediate(),执行将排在队列中已存在的任何 I/O 事件之后。

关于javascript - Node.js 中使用 setImmediate() 和 process.nextTick() 的意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28830663/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com