The execution sequence of async await and promise micro-tasks

problem description

Today I saw a problem about the execution order of js. I don"t know much about the timing of code execution after await in async await

  • question 1. Why is the promise2 and promise3 output earlier than the async1 end output? If they are all micro-tasks, didn"t async1 end join the micro-task queue first?
  • question 2. Why does async1 end precede promise4 output?

related codes

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")
}).then(function() {
  console.log("promise3")
}).then(function() {
  console.log("promise4")
}).then(function() {
  console.log("promise5")
}).then(function() {
  console.log("promise6")
}).then(function() {
  console.log("promise7")
}).then(function() {
  console.log("promise8")
})
console.log("script end")

chrome 70.0.3538.102 results

script start
async1 start
async2
promise1
script end
promise2 //  chrome canary 73 
promise3 //  chrome canary 73 
async1 end //  chrome canary 73 
promise4
promise5
promise6
promise7
promise8
setTimeout

Chrome canary 73.0.3646.0 (same as node8.12.0):

script start
async1 start
async2
promise1
script end
async1 end //  chrome 70 
promise2 //  chrome 70 
promise3 //  chrome 70 
promise4
promise5
promise6
promise7
promise8
setTimeout
Mar.09,2022

basic knowledge

before you look at the answer, I want you to at least know

  • The code in the executor (executor) of promise is
  • of Synchronize.
  • The callback of promise is microTask (micro task), while the callback of setTimeout is task (task / macro task)
  • microTask is executed before task.

simplify the topic

Let me simplify this question by deleting the code of Synchronize and the code of setTimeout before explaining it (some of the specifications of await have changed during this period).

to simplify, that's the problem:

After
  

reslove is called, promise2 is added to the task queue and Event Loop is executed once

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e4ba64-445d8.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e4ba64-445d8.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?