具体案例分析node事件环
time 4s
const fs = require('fs');
Promise.resolve()
.then(() => {
console.log(1);
});
process.nextTick(() => {
console.log(2);
});
console.log('start');
fs.readFile('1.txt', 'utf-8', () => {
setTimeout(() => {
console.log(3);
}, 0);
process.nextTick(() => {
console.log(4);
});
setImmediate(() => {
console.log(5);
});
console.log(6);
});
console.log(7);
setTimeout(() => {
console.log(8);
}, 0);
setImmediate(() => {
console.log(9);
});
console.log('end');
time 2m59s
const fs = require('fs');
Promise.resolve()
// promise1.then() cb
.then(() => {
console.log(1);
});
// nextTick1
process.nextTick(() => {
console.log(2);
});
console.log('start');
// readFile1
fs.readFile('1.txt', 'utf-8', () => {
// setTimeout2
setTimeout(() => {
console.log(3);
}, 0);
// nextTick2
process.nextTick(() => {
console.log(4);
});
// setImmediate2
setImmediate(() => {
console.log(5);
});
console.log(6);
});
console.log(7);
// setTimeout1
setTimeout(() => {
console.log(8);
}, 0);
// setImmediate1
setImmediate(() => {
console.log(9);
});
console.log('end');
time 4m31s
放入主执行栈中的任务完成,清空,开始执行微任务,主执行栈切换到timers的时候需要清空微任务,从timers切换到check时也需要清空微任务,切换需要清空微任务
每次从主执行栈中切换到别的任务都需要清空为任务,每一个阶段切换都需要清空微任务
走Times、poll、Check之前,要先清空微任务,虽然nextTick1是在 promise1.then() cb后面添加的,但nextTick1比promise先运行
time 9m04s
setTimeout 、setImmediate执行,cb放入执行栈,setImmediate cb可能先放入执行栈,setTimeout cb需要4ms放入执行栈,谁先谁后不一定,io中运行setImmediate一定先运行
setTimeout cb等主执行栈中的任务,清空了,走readfile
time 10m
readfile cb进入主执行栈
打印6,栈中有了任务
继续清空微任务,因为io中的setImmediate cb先执行