settimeout、promise、async的执行顺序

用一段代码来说明

async function async1() {
   console.log('async1 start')
   await async2()
   console.log('async1 end')
}
async function async2() {
   console.log('async2')
}
console.log('script start')
setTimeout(() => {
    console.log('setTimeout')
},0)
async1()
new Promise((resolve) => {
    console.log('promise1')
    resolve()
}).then(() => {
    console.log('promise2')
})
console.log('script end')

首先,定义了异步函数async1,但没有运行,往下定义了async2函数也没执行,再往下,输出script start, 之后settimeout是异步执行,先放到等待队列中,之后执行async1函数,输出async1 start, 之后等待async2执行完成,所以输出async2,而之后的则进入等待队列进行,之后先进行promise函数执行,先输出promise1.之后的则又进入等待队列,这时等待队列有三个,settimeout,async1的后半部分,还有promise的then中的函数,所以先输出script end ,注意了,由于promise的优先级比另外两个高,所以先输出promise2,再输出async1 end,最后输出 setTimeout
所以结果如下图

发布了16 篇原创文章 · 获赞 11 · 访问量 5733

猜你喜欢

转载自blog.csdn.net/Cirzearchenille/article/details/103430141