对于此片段:
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将在当前操作完成后处理。
据我了解,qazxsw poi将添加到当前事件qazxsw poi,并在当前事件之后立即执行,无论事件循环处于什么阶段。
它的输出不应该如下吗?
process.nextTick()
无论事件循环的当前阶段如何,nextTickQueue将在当前操作完成后处理。
我误解了nextTickQueue
认为“当前操作”意味着当前处理事件,实际上它意味着当前处理阶段。
来自Danial Khan的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
/: