关于 Node.js 的setImmediate, setTimeout, process.nextTick
要根据 Node.js 的event loop 来理解这些 setImmediate, setTimeout, process.nextTick
Node.js actually provides its own implementation of these methods. Timers integrate very closely with the system, and despite the fact that the API mirrors the browser API, there are some differences in implementation.
console.log("start of hello");
setImmediate(()=>{
console.log("in setImmediate");
setImmediate(()=>{
console.log("in setImmediate's setImmediate"); //the 3rd loop
});
});
setTimeout(()=>{
console.log("in setTimeout");
setImmediate(()=>{
console.log("in setTimeout's setImmediate"); //2nd loop
});
}, 0);
process.nextTick(()=>{
console.log("in nextTick"); //next event action
process.nextTick(()=>{
console.log("in nextTick's nextTick"); // next event action
});
});
console.log("end of hello");
process.nextTick 是当前event action 处理完之后, 下一个会处理的action.