一、说明
很多博客中,对于node的事件循环的概念都描述得非常详细,可是平时开发过程中很少涉及,所以每看一次都忘记一次,总的来说node的相关知识,我只消化了一张图+一道题。具体内容如下:
二、node执行流程图
同步的代码
|
process.nextTick / promise...
|
┌───────────────────────────┐
┌─>│ timers │ 定时器: setTimeout / setInterval
│ └─────────────┬─────────────┘
| process.nextTick / promise...
│ ┌─────────────┴─────────────┐
│ │ pending callbacks │ 执行延迟到下一个循环迭代的I/O回调
│ └─────────────┬─────────────┘
| process.nextTick / promise...
│ ┌─────────────┴─────────────┐
│ │ idle, prepare │ 系统内部使用
│ └─────────────┬─────────────┘ ┌───────────────┐
| process.nextTick / promise...
│ ┌─────────────┴─────────────┐ │ incoming: │
│ │ poll │<─────┤ connections, │
│ └─────────────┬─────────────┘ │ data, etc. │
| process.nextTick / promise...
│ ┌─────────────┴─────────────┐ └───────────────┘
│ │ check │ setImmediate
│ └─────────────┬─────────────┘
| process.nextTick / promise...
│ ┌─────────────┴─────────────┐
└──┤ close callbacks │ 关闭回调函数
└───────────────────────────┘
注意:
- process.nextTick 属于异步任务,但优先于promise
三、题型
async function async1() {
console.log('async1 started');
await async2();
console.log('async end');
}
async function async2() {
console.log('async2');
}
console.log('script start.');
setTimeout(() => {
console.log('setTimeout0');
setTimeout(() => {
console.log('setTimeout1');
}, 0);
setImmediate(() => {
console.log('setImmediate');
})
}, 0);
async1();
process.nextTick(() => {
console.log('nextTick');
})
new Promise((resolve) => {
console.log('promise1');
resolve();
console.log('promise2');
}).then(() => {
console.log('promise.then')
});
console.log('script end.');
执行结果:
script start -> async1 started -> async2 -> promise1 -> promise2 -> script end. ->
nextTick -> async end -> promise.then -> async end -> setTimeout0 -> setImmediate
-> setTimeout1
console.log(1)
setTimeout(() => {
console.log(2)
new Promise(resolve => {
console.log(4)
resolve()
}).then(() => {
console.log(5)
})
})
new Promise(resolve => {
console.log(7)
resolve()
}).then(() => {
console.log(8)
})
setTimeout(() => {
console.log(9)
new Promise(resolve => {
console.log(11)
resolve()
}).then(() => {
console.log(12)
})
})
// 浏览器中的结果:1、7、8、2、4 , 5、9、11、12
// Node 中的结果:1、7、8、2、4 , 9、11、5、12
解释:
其中,node的运行结果,由于node首先会进入poll阶段,
这是判断是否存在到达时间点的timer,若存在,则直接跳到timmer阶段,
把所有timer队列中的内容都执行完毕之后才进入下一阶段process.nextTick/promise。
参考博文:<https://blog.csdn.net/weixin_34191734/article/details/91470406>