一道题
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
遇到await表达式时,会先执行后面的表达式,然后返回一个Promise,接着跳出整个async函数来执行后面的代码,等后面的同步代码执行完了之后,再回到async函数中等待await表达式的返回值,如果不是一个Promise对象,则会有一个期待它resolve成为一个Promise对象的过程,然后加入队列中
如果上面将
async function async2(){
console.log('async2')
}
换成
function async2(){
console.log('async2')
}
返回结果:
script start
async1 start
async2
promise1
script end
async1 end // 注意这里
promise2 // 注意这里
setTimeout
网友评论