setImmediate()函数不会在process.nextTick()函数之后

时间:2018-09-12 00:57:58

标签: node.js event-loop libuv

此代码段:

const foo = [1, 2];
const bar = ['a', 'b'];

foo.forEach( num => {
  console.log(`setting setImmmediate ${num}`);
  setImmediate(() => {
    console.log(`running setImmediate ${num}`);
    bar.forEach(char => {
      console.log(`setting nextTick ${char}`);
      process.nextTick(() => {
        console.log(`running nextTick ${char}`);
      })
    })
  });
} )

输出为

$ node scratch.js                   
setting setImmmediate 1
setting setImmmediate 2
running setImmediate 1
setting nextTick a
setting nextTick b
running setImmediate 2
setting nextTick a
setting nextTick b
running nextTick a
running nextTick b
running nextTick a
running nextTick b

docs

  

当前操作完成后,无论事件循环的当前阶段如何,都将处理nextTickQueue。

据我了解,process.nextTick()将添加到当前事件的nextTickQueue中,并在当前事件之后立即执行,无论事件循环处于什么阶段。

输出不应该是以下内容吗?

setting setImmmediate 1
setting setImmmediate 2
running setImmediate 1
setting nextTick a
setting nextTick b
running nextTick a
running nextTick b
running setImmediate 2
setting nextTick a
setting nextTick b
running nextTick a
running nextTick b

1 个答案:

答案 0 :(得分:0)

  

当前操作完成后,将处理nextTickQueue,无论事件循环的当前阶段如何。

我误以为event loop documentation认为“当前操作”是指当前正在处理事件 ,而实际上是指当前正在处理< strong>阶段

摘自Danial Khan的What you should know to really understand the Node.js Event Loop /:

enter image description here