Why does 1 is printed before 4 in this execution of js code?

46 views Asked by At
async function check() {
  await Promise.resolve(console.log(1));
  console.log(2);
}
console.log(3);
check();
console.log(4);

The answer is 3,1,4,2

As I know the async function will go to web API to resolve and main program will execute first so I thought the output will be 3, 4 , 1 , 2 but that's wrong.

Can anyone explain this in terms of event loop and micro task queue how the correct answer is executed.

1

There are 1 answers

0
Sandeep M On

The event loop runs synchronous code first and then the asynchronous. So if you changed your function to await Promise.resolve().then(() => console.log(1)) then the output will be 3,4,1,2