Why async and await are needed in Javascript - Performance Analysis
When we use async and await in JavaScript, we want to handle tasks that take time without stopping everything else.
We ask: How does waiting for these tasks affect how long the program runs?
Analyze the time complexity of the following code snippet.
async function fetchData() {
const data1 = await fetch('url1');
const data2 = await fetch('url2');
return [data1, data2];
}
This code waits for two data fetches one after the other before continuing.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two fetch calls that wait for responses.
- How many times: Each fetch runs once, but they run one after another.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 2 (two fetches) | Wait for fetch 1 + wait for fetch 2 |
| 4 (four fetches) | Wait for fetch 1 + fetch 2 + fetch 3 + fetch 4 |
| 10 (ten fetches) | Wait for all 10 fetches one by one |
Pattern observation: Total wait time adds up because each fetch waits for the previous one to finish.
Time Complexity: O(n)
This means the total time grows directly with the number of async tasks done one after another.
[X] Wrong: "Using async and await makes tasks run at the same time."
[OK] Correct: Await pauses the code until the task finishes, so tasks run one after another, not together.
Understanding how async and await affect time helps you explain how programs handle waiting without freezing.
"What if we started all fetches without await, then awaited them all together? How would the time complexity change?"
Practice
async and await in JavaScript?Solution
Step 1: Understand the problem with slow tasks
Slow tasks like fetching data can freeze the program if handled synchronously.Step 2: Role of async and await
Async and await let the program wait for slow tasks without freezing, keeping it smooth.Final Answer:
To handle slow tasks without freezing the program -> Option BQuick Check:
Async/await = smooth waiting [OK]
- Thinking async/await makes code faster
- Believing async/await stops the whole program
- Confusing async/await with old browser code
Solution
Step 1: Recall async function syntax
The correct syntax placesasyncbefore thefunctionkeyword.Step 2: Check each option
Only async function fetchData() {} correctly usesasync function fetchData() {}.Final Answer:
async function fetchData() {} -> Option CQuick Check:
Async before function keyword [OK]
- Placing async after function name
- Adding async inside function parentheses
- Writing async after function body
async function greet() {
return 'Hello';
}
greet().then(console.log);Solution
Step 1: Understand async function return
An async function returns a Promise that resolves to the returned value.Step 2: Using .then to get value
The.then(console.log)prints the resolved value 'Hello'.Final Answer:
'Hello' -> Option AQuick Check:
Async function returns Promise, .then logs value [OK]
- Expecting direct string without .then
- Confusing Promise object with string
- Thinking async function returns undefined
async function fetchData() {
const data = await fetch('https://api.example.com');
return data.json();
}
const result = fetchData();
console.log(result);Solution
Step 1: Check fetchData() call
fetchData() returns a Promise, so logging it directly shows a Promise object.Step 2: Fix by awaiting fetchData()
Addingawaitbefore fetchData() inside an async context gets the resolved data.Final Answer:
Missing await before fetchData() call -> Option DQuick Check:
Await needed to get Promise result [OK]
- Logging Promise instead of awaited value
- Removing async keyword incorrectly
- Misunderstanding data.json() usage
function getUser() {
return fetch('/user').then(res => res.json());
}
function getPosts(userId) {
return fetch(`/posts?user=${userId}`).then(res => res.json());
}
// Fill in the blanks
async function loadData() {
const user = _____ getUser();
const posts = _____ getPosts(user.id);
console.log(posts);
}Solution
Step 1: Understand async function usage
Inside async functions, useawaitto wait for Promises step-by-step.Step 2: Apply await to both calls
BothgetUser()andgetPosts()return Promises, so both needawait.Final Answer:
await, await -> Option AQuick Check:
Use await for sequential async calls [OK]
- Mixing then and await inside async function
- Forgetting await causing Promise logs
- Using then without returning inside async
Ready to prove it?
Pass the test and this pattern moves unknown
