gpt4 book ai didi

javascript - 为什么以及何时使用 process.nextTick?

转载 作者:数据小太阳 更新时间:2023-10-29 03:53:25 26 4
gpt4 key购买 nike

下面是“practise01.js”文件中的代码,

function fn(name){
return f;

function f(){
var n = name;
console.log("Next TICK "+n+", ");
}
}

function myTimeout(time,msg){
setTimeout(function(){
console.log("TIMEOUT "+msg);
},time);
}

process.nextTick(fn("ONE"));
myTimeout(500,"AFTER-ONE");
process.nextTick(fn("TWO"));
myTimeout(500,"AFTER-TWO");
process.nextTick(fn("THREE"));
myTimeout(500,"AFTER-THREE");
process.nextTick(fn("FOUR"));

运行上面代码的输出是

rahul@rahul:~/myPractise/PlainNodeJSPractise01/Process$ node practise01.js                  

Next TICK ONE,
Next TICK TWO,
Next TICK THREE,
Next TICK FOUR,
TIMEOUT AFTER-ONE
TIMEOUT AFTER-TWO
TIMEOUT AFTER-THREE

现在我在“practise02.js”中不使用process.nextTick写了代码,如下,

function myTimeout(time,msg){
setTimeout(function(){
console.log("TIMEOUT "+msg);
},time);
}

function fn(name){
return f;

function f(){
var n = name;
console.log("Next TICK "+n+", ");
}
}

fn("ONE")();
myTimeout(500,"AFTER-ONE");
fn("TWO")();
myTimeout(500,"AFTER-TWO");
fn("THREE")();
myTimeout(500,"AFTER-THREE");
fn("FOUR")();

运行上述代码后输出为

rahul@rahul:~/myPractise/PlainNodeJSPractise01/Process$ node practise02.js 
Next TICK ONE,
Next TICK TWO,
Next TICK THREE,
Next TICK FOUR,
TIMEOUT AFTER-ONE
TIMEOUT AFTER-TWO
TIMEOUT AFTER-THREE

如果您看到两个输出相同。

那么在哪种情况下我需要使用 process.nextTick ?

当我尝试阅读更多内容时,我开始明白如果我需要在 eventloop 为空时立即执行某些功能而不是去“process.nextTick”。

那么它与我的第二种方法有何不同。

请解释或给我一些指示

最佳答案

Node 文档实际上很好地解释了何时以及为何使用 nextTick:

https://nodejs.org/api/process.html#process_process_nexttick_callback_args

它的作用:

This is not a simple alias to setTimeout(fn, 0), it's much more efficient. It runs before any additional I/O events (including timers) fire in subsequent ticks of the event loop.

以及何时使用:

This is important when developing APIs in order to give users the opportunity to assign event handlers after an object has been constructed but before any I/O has occurred...

function definitelyAsync(arg, cb) {
if (arg) {
process.nextTick(cb);
return;
}

fs.stat('file', cb);
}
definitelyAsync(true, () => {
foo();
});
bar(); // will now allways be called before foo()

关于javascript - 为什么以及何时使用 process.nextTick?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40629456/

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