DEV Community

Cover image for Wierd Async/Await Behaviour in JS 🤔
stagefright5
stagefright5

Posted on

Wierd Async/Await Behaviour in JS 🤔

Apparently the non async code inside an async function will execute synchronously even if you don't await.
Consider this code example:

async function f() {
    g('adsasdasd'); // note that it is not `await`ed
    console.log('000');
}

async function g(m) {
    console.log('g', m);
}

f() // calling `f`
Enter fullscreen mode Exit fullscreen mode

I always thought it would produce this output:

000
g adsasdasd
Enter fullscreen mode Exit fullscreen mode

BUT, the actual output is like this

g adsasdasd // function `g` is executed first!!
000
Enter fullscreen mode Exit fullscreen mode

Can anyone explain this?

Top comments (1)

Collapse
 
vishalraj82 profile image
Vishal Raj

The return value of an async function is always an Promise. Here function g is technically returning undefined, but before that its executing console.log which is a simple log statement. Hence it prints the string. The subsequent call to console.log(000) prints another value.