0
0
Javascriptprogramming~5 mins

Why async and await are needed in Javascript - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why async and await are needed
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows directly with the number of async tasks done one after another.

Common Mistake

[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.

Interview Connect

Understanding how async and await affect time helps you explain how programs handle waiting without freezing.

Self-Check

"What if we started all fetches without await, then awaited them all together? How would the time complexity change?"