DEV Community

Cover image for Wierd Async/Await Behaviour in JS πŸ€”
stagefright5
stagefright5

Posted on

1 1

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.

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay