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?"