What is the order in which async await is executed?

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

the execution order of the above code is

async1 start -> async2 -> promise1-> script end -> promise2 -> async1 end -> setTimeout

what"s more confusing here is the order of promise2 and async1 end.

see a material saying that when async2 is executed, a promise object will be returned and placed in the task queue, and then when the synchronous task is completed, the promise object just mentioned in the task queue will be executed. then it encounters the resolve function, and then it is put into the task queue and jumps out of the async1 function . Then the console in then is executed, and finally console.log ("async1 end")

is executed. Why do you jump out of the resolve function when you encounter the async1 function in the

bold area?

Jul.19,2022

is it possible that the data is miswritten. The result I ran out with the latest version of Google browser is async1 start- > async2- > promise1- > script end- > async1 end- > promise2- > setTimeout
async1 end and promise2 are placed in the micro-task queue, await also returns promise, both micro-tasks are triggered by .then, so they should not have priority, but should be executed in the order of joining the queue.

Menu