This is the fourth day of my participation in the August More text Challenge. For details, see:August is more challenging

“Async function async1() {console.log(‘ async1 start ‘); Await async2 (); The console. The log (‘ async1 end ‘)”

Write the output of the following program:

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');
});
console.log('script end');
Copy the code

Output results:

script start
async1 start
async2
promise1
script end
async1 end
promise2
setTimeout
Copy the code

Step analysis:For the order of execution, see here

  • First, the event loop starts from the macrostack (macrostack) queue. At this point, there is only one script (overall code) task () in the macro (overall script, setTimeout, setInterval) queue.
  • First execute console.log(‘script start’), output ‘script start’
  • Put console.log(‘setTimeout’) in macroTask queue when setTimeout is encountered
  • Execute aync1() to output ‘async1 start’ and ‘async2’ and put console.log(‘async1 end’) in the micro queue
  • Execute to promise, output ‘promise1’, put console.log(‘promise2’) in micro queue
  • Execute console.log(‘script end’), output ‘script end’
  • Macrotask will execute microtask, microtask quene will execute microtask all at once, so output ‘async1 end’ and ‘promise2’
  • Start a new round of event loop, remove a macroTask execution, so output ‘setTimeout’

Related knowledge:

  • The Promise takes precedence over the setTimeout macro task, so the setTimeout callback is executed last
  • Once a Promise is defined, it is immediately executed
  • Resolve and Reject of promises are callbacks that are executed asynchronously. So resolve() is put on the callback queue and called before the main function finishes executing and before setTimeout
  • After the await completes execution, the thread is released. A function marked async returns a Promise object