Welcome to Qi-U Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

JavaScript async/await 中执行顺序问题

async function async1() {
     console.log("async1 start");
    await async2();
    console.log("async111 end"); // 为什么在 console.log("start")后执行
}
async function async2() {
    setTimeout(() => {
        console.log("timer")
    }, 0)
    console.log("async2")
}
async1()
console.log("start")

输出结果
async1 start
async2
start
async111 end
undefined
timer


第3个输出结果为什么是 start 而不是 async111 end
为什么 async1 函数还没有执行到第二个 console.log 就输出了调用 async1() 函数后面的 console.log("start")?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

async/await 是Promise的语法糖。

await async2();
console.log("async111 end"); 
// 相当于
Promise(()=>{
    async2(); // Promise中的函数是会立即执行的
}).then(()=>{
    console.log("async111 end"); 
})

Promise.then 是微任务,是在执行完一个宏任务队列后再清空执行的。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Qi-U Community for programmer and developer-Open, Learning and Share
...