// 代码一开始就执行宏任务-宏0
console.log('script start')
setTimeout(() => {
console.log('北歌')
}, 1 * 2000)
Promise.resolve()
.then(function () { // 微1-1
console.log('promise1')
})
.then(function () { // 微1-4 这个then中的会等待上一个then执行完成之后得到其状态才会向Queue注册状态对应的回调,假设上一个then中主动抛错且没有捕获,那就注册的是这个then中的第二个回调了。
console.log('promise2')
})
async function foo () {
await bar()
console.log('async1 end') // 微1-2
}
foo()
async function errorFunc () {
try {
await Promise.reject('error!!!111')
} catch (e) {
// => 从这后面开始所有的代码可以理解为放到异步队列微任务中
console.log(e) // 微1-3
}
console.log('async1')
return Promise.resolve('async1 success')
}
errorFunc().then(res => console.log(res))
function bar () {
console.log('async2 end')
}
console.log('script end')
// 第一次执行:
// 全局一个宏任务执行, 输出同步代码。挂载宏1、微1-1、微1-2、微1-3、微1-4。1-表示属于第一次轮询
// run: script start、 async2 end、script end
// 第二次执行:
// 同步代码执行完毕,开始执行异步任务中的微任务对列中的代码
// 微任务列表:只有一个队列且会在当前轮询一次清空
// run:
// 执行微1-1: promise1
// 执行微1-2: async1 end
// 执行微1-3: error!!!、async1 。当前异步回调执行完毕才Promise.resolve('async1 success'),然后注册then()中的成功的回调-微1-5
// 执行微1-4: promise2
// 执行刚刚注册的微1-5: async1 success
// 第三次执行
// 开启第二波轮询:执行宏1
// run: '北歌'