Async function without await in Javascript

Ulysse BN picture Ulysse BN · Aug 9, 2017 · Viewed 89.2k times · Source

I have two functions a and b that are asynchronous, the former without await and the later 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.

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.

So my question is: how 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:

async function initializeComponent(stuff) {
   if (stuff === undefined)
      stuff = await getStuff()
   // initialize

   if (/* context has been blocked */)
       renderComponent() // render again if stuff had to be loaded
}

initializeComponent()
renderComponent()

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

Answer

Karim picture Karim · Aug 9, 2017

mozilla doc:

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 in a non-blocking manner.