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