Do Async Functions Begin Synchronously?

Consider the following example:

async function a() {
  console.log('a');
  return new Promise(...)
}

a();
console.log('b');

In which order will 'a' and 'b' be printed to the console?

Will the call to a() get pushed into the event queue, causing the main thread to run console.log('b') before executing the call to a()?

Or is it simply that the final, returned promise in a() is what gets run asynchronously, ensuring that all non-async code within a() runs before switching back to the main body of code?

Let me break it down step by step:

When an async function is called, it executes synchronously until it encounters an await statement or returns a promise. This means that any code before an await or a return statement runs immediately.

Inside a(), the console.log('a') statement is executed immediately and synchronously. There's no await before this line, so it runs right away. This guarantees that 'a' is printed to the console as soon as a() is called.

After printing 'a', the function prepares to return a new promise. This is where the asynchronous behavior starts. The promise's resolution is deferred to the event loop, allowing the function to exit and execution to continue without waiting for the promise to resolve.

With the asynchronous operation pending, control returns to the caller, and console.log('b') is executed, printing 'b' to the console.

Understanding this nuanced behavior of async functions is crucial for writing effective JavaScript code. It helps in structuring your functions to leverage both synchronous and asynchronous execution efficiently.

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda