最近看了很多eventLoop方面的东西,但是一直都没有看明白,今天面试被问到了,回答的也不好,面试官还给讲解了一下,是个很好的人啊,但是总感觉不对,回家之后又继续看和研究,感觉自己好像明白了,记录一下
setTimeout(()=>{
console.log('3')
Promise.resolve().then(()=>{
console.log(4)
})
},0)
Promise.resolve().then(()=>{
console.log('1')
setTimeout(()=>{
console.log('2')
},0)
})
1
3
4
2
宏任务:setTimeout,setInterval
微任务:promise.then()
console.log('script start')
async function async1() {
await async2()
console.log('async1 end')
}
async function async2() {
console.log('async2 end')
}
async1()
setTimeout(function() {
console.log('setTimeout')
}, 0)
new Promise(resolve => {
console.log('Promise')
resolve()
})
.then(function() {
console.log('promise1')
})
.then(function() {
console.log('promise2')
})
console.log('script end')
script start
async2 end
Promise
script end
async1 end
promise1
promise2
setTimeout
这段代码里awaitf执行后返回的是个promise,await后续的代码会被挂起,个人理解类似promise.then,变成了一个微任务,先进入微任务队列。但是感觉new Promise是同步任务,先执行new Promise里的内容,后续then的进入微任务队列。
个人理解:在任务执行的时候,先执行同步任务,期间出现的宏任务和微任务分别进入宏任务和微任务队列,在同步任务执行结束后,会先清空微任务队列,然后执行一个宏任务(队列先进先出),在次清空微任务,依次循环,我的理解是每执行一个宏任务,就会清空一次微任务