process.nextTick()的理解

来源:互联网 发布:做报刊的软件 编辑:程序博客网 时间:2024/05/16 02:27

      process.nextTick() 实际上在事件循环中执行了下一个事件,才返回处理当前事件,当前事件被阻止进行。

     在《node.js开发指南》一书中,对process.nextTick(callback)的功能解释是”为事件循环设置一项任务,node.js会在下次事件循环调响应时调用callback”.    

        Kishore Nallan的文章《Understanding process.nextTick()》(https://howtonode.org/understanding-process-next-tick)中写到“ every Node application runs on a single thread.”,node.js的进程只有一个,因此在任何时候都只有一个事件在执行,所以要尽量缩短每个事件的执行时间,process.nextTick()提供了一个这样的工具,可以把复杂的工作拆散,变成一个一个较小的事件。

     “You can imagine this event loop to be a queue of callbacks that are processed by Node on everytick of the event loop.”你可以想象这个事件循环是一个队列,触发回调。

      node.js的官方文档中(https://nodejs.org/api/process.html#process_process_nexttick_callback_args)写道“It runs before any additional I/O events (including timers) fire in subsequent ticks of the event loop.”它在任何其他I / O事件(包括定时器)在事件循环的后续tick中触发时运行,

     “This is important when developing APIs in order to give users the opportunity to assign event handlersafter an object has been constructed but before any I/O has occurred:”在开发API的时候,当一个对象构造成功,任何I/O操作都没开始时, 给使用者权利去分配事件的处理非常重要。

function MyThing(options) {  this.setupOptions(options);  process.nextTick(() => {    this.startDoingStuff();  });}var thing = new MyThing();thing.getReadyForStuff();

process.nextTick()比setTimeout(fn, 0). 更高效

“As a result, recursively setting nextTick callbacks will block any I/O from happening”因此,递归设置nextTick回调将阻止任何I / O发生,一直事件循环下去,依次处理,最后处理 I/O 操作,线程不会被 I/O 阻塞,cpu一直处于被利用的状态,这就是node.js单线程异步式 I/O 编程的好处。

0 0
原创粉丝点击