Synchronous vs asynchronous
๐ First, what does async/await do?
-
asyncmakes a function return a Promise. -
awaitpauses the execution inside theasyncfunction until the awaited Promise resolves โ but it does not block the rest of the program.
๐ง So how is it asynchronous?
๐ Async/Await Step-by-Step Example
Let's break it down step by step:
console.log("1. Start");
async function fetchData() {
console.log("2. Inside async function");
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
console.log("4. After await");
const data = await response.json();
console.log("5. Data:", data);
}
fetchData();
console.log("3. End");
๐งช Output:
1. Start
2. Inside async function
3. End
4. After await
5. Data: { ... }
๐ Why this output?
-
console.log("1. Start")โ runs immediately -
fetchData()is called โ enters the async function -
console.log("2. Inside async function")โ runs -
await fetch(...)is asynchronous, so:-
JS pauses
fetchData()here -
JS continues with the next line:
console.log("3. End")
-
-
Once the fetch resolves,
fetchData()resumes and logs "4" and "5".
๐ So what makes it async?
-
awaitdoesn't block the whole program, only suspends execution of the async function. -
JS uses an event loop to handle this:
- After hitting
await, JS registers the remaining code (callback) to run later, when the Promise resolves.
- After hitting
๐ Visualization
โ Start Program
โ Run until await
โ Pause function
โ Continue with rest of the code
โ When Promise resolves
โ Resume async function from where it left