以下是“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”。

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

请给我解释或给我一些指导

最佳答案

您在自己的帖子中有答案,并在以下位置与我们分享您的输出:

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-THRE

如果我们将您的超时间隔从500更改为0,结果仍然相同:

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(0,"AFTER-ONE");// set timeout to execute in 0 seconds for all
process.nextTick(fn("TWO"));
myTimeout(0,"AFTER-TWO");
process.nextTick(fn("THREE"));
myTimeout(0,"AFTER-THREE");
process.nextTick(fn("FOUR"));


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

当您使用process.nextTick时,基本上可以确保在下一个刻度即即立即调用作为参数传递的函数。下一个事件循环的开始。这就是为什么下一个滴答中的所有功能都在计时器之前执行的原因。 setTimeout next tick并不意味着下一秒,它意味着nodejs eventloop的下一个循环。另外,下一个刻度将确保您尝试调用的函数是异步执行的。而且下一个节拍比在事件循环中排队执行的计时器,I/O操作等具有更高的优先级。如果要确保代码在下一个事件循环中执行,而不是在指定的时间之后执行,则应使用nextTick。 nextTick比计时器更有效,并且当您要确保调用的函数是异步执行时。您可以在nodejs docs中找到有关此信息的更多信息。

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

10-10 11:37