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
In your code only
hello
worked as async function.You defile
fun
function as async function, but it didn’t work because when you callfun
, you don’t useawait
.I add code below.
In
JavaScript
, when an asynchronous function is called, it doesn’t block the execution of subsequent code. Theawait
keyword inside anasync
function causes the function to pause and wait, but it doesn’t block the execution of other code outside theasync
function. This is why "End" is printed before "Hello".