Skip to content
Advertisement

Async function without await in JavaScript

I have two functions, a and b, that are asynchronous, the former without await and the latter with await. They both log something to the console and return undefined. After calling either of the function, I log another message and look if the message is written before or after executing the body of the function.

JavaScript
JavaScript

If you launch test without await, the function seems to work as if it was synchronous. But with await, the messages are inverted as the function is executed asynchronously.

How does JavaScript execute async functions when no await keyword is present?


Real use case: I have an await keyword which is conditionally executed, and I need to know if the function is executed synchronously or not in order to render my element:

JavaScript

P.S: The title has the JavaScript keyword to avoid confusion with the same questions in other languages (i.e Using async without await)

Advertisement

Answer

Mozilla documentation:

An async function can contain an await expression, that pauses the execution of the async function and waits for the passed Promise’s resolution, and then resumes the async function’s execution and returns the resolved value.

As you assumed, if no await is present, the execution is not paused and your code will then be executed synchronously as normal.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement