JavaScript Async/Await Notes
JavaScript: Async/Await and Execution Flow
JavaScript is synchronous in nature.
This means it executes code line by line, one at a time.
But it supports asynchronous operations like:
- setTimeout
- Promises
- async/await
- DOM events
These are handled by the JavaScript runtime using callback queues and the event loop.
Event Loop Concept:
When asynchronous code is encountered (like a Promise or DOM event):
1. JavaScript registers the task with the browser/runtime.
2. The rest of the synchronous code continues to execute.
3. Once the async task completes, it goes to the **callback queue**.
4. The **event loop** constantly checks if the call stack is empty.
If it is, it pushes the task from the queue to the call stack.
Corrected Statement:
"JavaScript is synchronous by nature, but when asynchronous code (like Promises or DOM events)
is encountered, it delegates the task to the runtime to execute in the background. Meanwhile,
synchronous code continues to run. Once the async task finishes, it is pushed into the callback
queue, and the event loop ensures it runs only after synchronous tasks complete."
Example:
async function fetchData() {
const data = await fetch("[Link]
[Link]("Data:", data);
[Link]("Start");
fetchData();
[Link]("End");
Output:
Start
Inside fetchData - 1
End
Inside fetchData - 2 (after data is fetched)
"await" only pauses the execution **inside the async function**, not outside.
Meaning of: "Pauses only inside the async function"
Only the code after `await` is paused inside that function. Other code (outside the function)
continues immediately.