代码如下
setTimeout(() => { console.log('timeout1') Promise.resolve().then(()=>{ console.log('reslove1') })}, 0)setTimeout(() => { console.log('timeout2') Promise.resolve().then(()=>{ console.log('reslove2') })}, 0)setImmediate(()=>{ console.log('setImmediate1')})setImmediate(()=>{ console.log('setImmediate2')})Promise.resolve('resolve3').then((data)=>{ console.log(data)})复制代码
输出结果如下:
Node.js 中事件循环分为6个阶段,setTimeout在timers阶段执行,setImmediate在check阶段执行由于settimeout在timers阶段执行顺序不确定,按我的理解,结果有两种
1.settimeout在当前事件循环执行,输出结果:
'timeout1'>'timeout2'>'resolve3'>'resolve1'>'resolve2'>'setImmediate1'>'setImmediate2'复制代码
2.settimeout在下一个事件循环执行,输出结果:
'resolve3'>'setImmediate1'>'setImmediate2'>'timeout1'>'timeout2'>'resolve1'>'resolve2'复制代码
为何最后结果为,并且结果很稳定:
'resolve3'>'timeout1'>'timeout2'>'resolve1'>'resolve2'>'setImmediate1'>'setImmediate2'复制代码
去掉promise之后,输出结果为
跟预期中一样,结果随机,想来重点是promise造成了影响求各位大牛指教下!!!谢谢!!!