Although the async/await
syntax provides a way to write asynchronous code that looks like synchronous code, it is important to understand that it is processed asynchronously under the hood. This means that the await
expression does not actually block the main thread; instead, it defers the execution of the code that depends on its result.
When using await
within an async
function, it temporarily pauses the execution of that function until the awaited Promise is resolved. However, during this pause, the event loop is free to execute other tasks or code that is not dependent on the awaited Promise. This concurrency enables the application to remain responsive and prevents the main thread from being blocked.
For example, consider the following code:
async function fetchData() { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const data = await response.json(); console.log(data); // this will be printed second } fetchData(); console.log('synchronous log message'); // this will be printed first
In this code, the console.log
statement after fetchData()
is executed before the console.log
inside the fetchData()
function. This demonstrates the asynchronous behavior of async/await
.
It's worth noting that async/await
is essentially syntactic sugar built on top of JavaScript promises. Therefore, the code above can be visualized as equivalent to the following promise-based code:
function fetchData() { fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .then(data => { console.log(data); // this will be printed second }); } fetchData(); console.log('synchronous log message'); // this will be printed first
Regardless of the syntax used, while awaiting the completion of asynchronous operations, the event loop ensures that other tasks, events, or code can continue to be executed, preserving the application's responsiveness.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.