Search code examples
javascriptnode.jsconcurrencyasync-awaitv8

why 2 and 4 prints before b prints?


function first() {
  return new Promise(resolve => {
    console.log(2);
    resolve(3);
    console.log(4);
  });
}

async function f() {
  console.log(1);
  let r = await first();
  console.log(r);
  console.log(99);
}

console.log('a');
f();
console.log('b');

In the above code shows the following result:

a
1
2
4
b
3
99

In my understanding, when the compiler hits the await first() function, it pushes the first() function execution to the event queue and pause the execution of f(), continue execution everything after f().So the execution order should be:

a
1
b
2
4
3
99

Apparently, I get it wrong. Can anyone explain to me how this is really working?


Solution

  • enter image description here

    enter image description here

    if you didn't understand ,leave a comment . Thank you.