经典面试题
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
promise2
async1 end
setTimeout
4、分析过程
1.定义一个异步函数 async1
2.定义一个异步函数 async2
3.打印 ‘script start’ // *1
4.定义一个定时器(宏任务,优先级低于微任务),在0ms 之后输出
5.执行异步函数 async1
1.打印 'async1 start' // *2
2.遇到await 表达式,执行 await 后面的 async2
2.1打印 'async2' // *3
3.返回一个 Promise,跳出 async1 函数体
6.执行 new Promise 里的语句
1.打印 ‘promise1‘ // *
2.resolve() , 返回一个 Promise 对象,把这个 Promise 压进队列里
7.打印 ’script end’ // *
8.同步栈执行完毕
9.回到 async1 的函数体,async2 函数没有返回 Promise,所以把要等async2 的值 resolve,把 Promise 压进队列
10.执行 new Promise 后面的 .then,打印 ’promise2‘ // *6
11.回到 async1 的函数体,await 返回 Promise.resolve() ,然后打印后面的 ’async1 end‘ // *7
12.最后执行定时器(宏任务) setTimeout,打印 ’setTimeout‘ // *8
那么现在,我们是不是大致上对async / await 理解了呢,我们来改一下这道题再来看看,把 async2 改造一下
改造的题目如下:
async function async1(){
console.log('async1 start')
await async2()
console.log('async1 end')
}
function async2(){ // 去掉了 async 关键字
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