Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

code inside async function executes before the code that follows it

I'm currently exploring the concept of async/await in javascript.I know that async function returns a promise which supposed to resolve in a future time and it doesn't block the natural execution of code.Here I have a code which i wrote to test the async execution of javascript.

console.log("1")
async function asyncFunc(){
  for(i=0;i<10000000;i++){
  }
  console.log("3")
}
asyncFunc().then(()=>{console.log('4')});
console.log("2");

I except the code will be executed in the following fashion:

first console.log() prints 1

secondly async function is called. As async code is non blocking,last console.log() will execute and thus prints 2 in the console.

After that console.log() inside async function will be executed and will print 3 in console.

lastly the promise will be resolved and console.log() inside then will be executed and prints 4.

so expected output : 1,2,3,4

but in reality I get output as 1,3,2,4.

why it behaves like this and not the way I expected

like image 206
AL-zami Avatar asked Jun 25 '26 08:06

AL-zami


1 Answers

The function doesn't return a promise until it has finished running (unless you await another promise inside it).

The loop runs (blocking everything), then console.log("3") is evaluated, then it returns a promise.

The calling function continues to run (logging 2).

Finally, the event loop is freed up and the function passed to then is called.

Marking a function as async doesn't turn synchronous code inside it into asynchronous code.

like image 51
Quentin Avatar answered Jun 27 '26 20:06

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!