-2

I want to understand what Async function do in js. If it actually runs code asynchronously then it should keep executing the code which is written after function call.

My code:

async function someWork(){

            let p=10;
            console.log("inside someWork");
            //Some calculations to spend time
            for(let i=0;i<100000000;i++){
                b=i**i;
                if(i==100000000-2){
                    console.log(i+" last Iteration, about to complete the calculation..");
                }
            }
            console.log(p+" I am done With Long work");
        }
        
        console.log("before calling somework async function");
        someWork();
        console.log("after calling somework async function");

output:

 before calling somework async function
 inside someWork
 99999998 last Iteration, about to complete the calculation..
 10 I am done With Long work
 after calling somework async function

However what I am expecting is:

 before calling somework async function
 after calling somework async function
 inside someWork
 99999998 last Iteration, about to complete the calculation..
 10 I am done With Long work

1 Answers1

0

If it actually runs code asynchronously...

An async function does not execute asynchronously. It runs synchronously, but returns a promise. Declaring a function with async only makes sense when it uses the keyword await, because that will be the point where the function returns to continue with the code after the function call, leaving the rest of its code for later, asynchronous execution.

For your desired output, there are many options:

  1. Insert the line await null; at the top of your async function.

  2. Don't use async and have your function called by setTimeout, requestAnimationFrame, queueMicrotask, or any other asynchronous API.

  3. Create a Web Worker, and have the function executed by it. This will have the function executed by a different thread, potentially giving more concurrency.

trincot
  • 317,000
  • 35
  • 244
  • 286