skip to Main Content

I am learning Javascript and I came across of JS snippet. I don’t understand how it works

let hello = () => Promise.resolve("Hello")

async function fun() {
  console.log("Inside")
  const result = await hello()
  console.log(result)
}

console.log("Start")
fun()
console.log("End")

The result in the console

Start
Inside
End
Hello

I don’t understand why End is printed before Hello despite the await keyword used. I would like to understand how this snippet would work in the event loop. More specifically what happens when fun() is pushed into the call stack

2

Answers


  1. In your code only hello worked as async function.

    You defile fun function as async function, but it didn’t work because when you call fun, you don’t use await.

    I add code below.

    let hello = () => Promise.resolve("Hello");
    
    async function fun() {
      console.log("Inside");
      const result = await hello();
      console.log(result);
    }
    
    const main = async () => {
      console.log("Start");
      await fun();
      console.log("End");
    };
    main();
    Login or Signup to reply.
  2. In JavaScript, when an asynchronous function is called, it doesn’t block the execution of subsequent code. The await keyword inside an async function causes the function to pause and wait, but it doesn’t block the execution of other code outside the async function. This is why "End" is printed before "Hello".

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search