宏任务有Event Table、Event Queue,微任务有Event Queue
- 宏任务:包括整体代码script,setTimeout,setInterval
- 微任务:Promise,process.nextTick
注:Promise立即执行,then函数分发到微任务Event Queue,process.nextTick分发到微任务Event Queue
示例
输出下面代码的执行顺序
console.log('one')
setTimeout(function(){
console.log('two')
},0)
new Promise(function(resolve,reject){
console.log("three")
resolve()
}).then(function(){
console.log('four')
})
console.log('five');
得到的结果是: one three five three two
代码解释
- 执行外层宏任务1 console.log 输出=>one
- 遇到 Promise直接执行 输出 外层宏任务2 输出=>three 执行then 被分发到微任务Event Queue中
- 执行同步操作 遇到外层宏任务3 console.log 输出=>five
- 外层宏任务执行完成 开始执行被挂起的Promise微任务console.log 输出=>four
- 继续执行第二轮宏任务 输入setTimeout中的宏任务 输出=>two
感谢遇见 谢谢大神的指点 这里仅是个人学习成长日记