我正在阅读https://nodejs.dev/en/learn/understanding-process-nexttick/最后一句话是:
当您希望确保在下一个事件循环迭代中该代码已经执行时,请使用nextTick((。
但在此之前,它说:
调用setTimeout(((=>{},0(将在下一个刻度结束时执行该函数,比使用nextTick((时要晚得多,后者会优先考虑调用并在下一刻度开始前执行。
现在我有点困惑,为什么要使用nextTick()
来确保代码在下一次勾选之前已经执行?setTimeout()
中定义的代码是否不能保证执行?
setTimeout(((=>{},0(将在nextTick((之后执行函数
setTimeout(((=>{},0(执行需要时间,您可以在下面的输出中看到差异。
//setTimeout
setTimeout(() => {
console.log('Executed this in the next iteration');
}, 0);
console.log('Executed this in the current iteration');
//See Output ----->
Executed this in the current iteration
connected to port: 2020
Executed this in the next iteration
nextTick((对调用进行优先级排序,并在下一个tick开始之前执行它。
//nextTick
process.nextTick(() => {
console.log('Executed this in the next iteration');
});
console.log('Executed this in the current iteration');
//See Output ----->
Executed this in the current iteration
Executed this in the next iteration
connected to port: 2020