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.
I have created a set of resources for learning asynchronous JavaScript. These guides—Callbacks, Promises, and Async/Await —cover everything I’ve learned from years of real-world JavaScript experience.
If you found this article helpful, you’ll get so much out of these guides. Each one is optimized for those “lightbulb moments,” building a strong mental model for how asynchronous JavaScript works and how you can use it to create fast, dynamic applications.