Search code examples
javascriptasync-awaitpromisees6-promise

Not getting what's happening in the JavaScript script code below


async function async1(){
  console.log(1)
  await async2()
  console.log(2)
}

async function async2(){
  console.log(3)
}

console.log(4)

setTimeout(function(){
  console.log(5)
}, 0)

async1()

new Promise(function(resolve){
  console.log(6)
  resolve()
}).then(function(){
  console.log(7)
})

console.log(8)

4
1
3
6
8
7
2
5

Please explain how this code creating the above output. I'm confused with Why the 2 not come immediately after log(3). what is exactly happening after we use async await ?. please provide some insights on this.


Solution

  • Since you are not doing await on async1 method invocation (async1()), The control will be on current execution context and console.log(2) will be moved to micro task queue in event loop.

    Please execute your code again with changing await async2() in browser console and you will notice the expected order.

    enter image description here

    Update: Adding more details

    The async functions return the promise. When using await for async function execution means, the rest of code after the await will be executed after the async promise resolve.

    To see the execution flow, I have converted to equivalent code which using directly promises.

    console.log(4);
    
    setTimeout(function () { // move to call back queue
      console.log(5);
    }, 0);
    
    new Promise(function () {
      console.log(1);
      new Promise(function (resolve) {
        console.log(3);
        resolve();
      }).then(function () { // move to micro task queue
        console.log(2);
      });
    });
    
    new Promise(function (resolve) {
      console.log(6);
      resolve();
    }).then(function () { // move to micro task queue
      console.log(7);
    });
    
    console.log(8);