异步笔试题,请写出下面代码的运行结果:
async function async1() {
console.log('async1 start');
await async2();
console.log('async1 end');
}
async function async2() {
console.log('async2');
}
console.log('script start');
setTimeout(function() {
console.log('setTimeout');
}, 0)
async1();
new Promise(function(resolve) {
console.log('promise1');
resolve();
}).then(function() {
console.log('promise2');
});
console.log('script end');
/*
script start
async1 start
async2
promise1
script end
async1 end
promise2
setTimeout
*/
这道题考的知识点:
- js事件循环机制
- 同步异步执行顺序
- 微任务宏任务
- async await知识
我的问题:async await相关的执行顺序理解错误
总结记录:async await相当于是一个promise的语法糖,转换成promise再结合微任务宏任务相关知识可以得出正确答案
async function async1() {
console.log('async1 start');
await async2();
console.log('async1 end');
}
// 等价于
async function async1() {
console.log('async1 start');
Promise.resolve(async2()).then(() => {
console.log('async1 end');
})
}
网友评论