await,async,宏任务和微任务
创建:2022-07-19 18:20 更新:2022-07-19 18:20
async function async1() {
console.log('async1 start')//1
await async2()
console.log('async1 end')//2
}
async function async2() {
new Promise(resolve => {
console.log('promise1')//3
resolve()
})
.then(() => {
console.log('promise2')//4
})
}
console.log('script start')//5
setTimeout(() => {
console.log('setTimeout')//6
}, 0);
async1()
new Promise(resolve => {
console.log('promise3')//7
resolve()
})
.then(() => {
console.log('promise4')//8
})
console.log('script end')//9
1.首先执行代码5,输出"script start"; 2.遇到setTimeout,将代码6放入下次宏任务队列; 3.函数async1,执行代码1输出"async1 start"; 4.函数async2,存在修饰符await会阻塞代码运行,先执行函数async2; 5.函数新建Promise对象,执行代码3输出"promise1",将代码4放入微任务队列; 6.将函数async2后的代码2放入微任务队列; 7.新建Promise对象,执行代码7输出"promise3",并将代码8放入微任务队列; 8.执行代码9,输出"script end"; 9.按顺序清空微任务,依次执行代码4、代码2、代码8; 10.按顺序情况宏任务,执行代码6;
运行结果:
script start
async1 start
promise1
promise3
script end
promise2
async1 end
promise4
setTimeout