0
0
Javascriptprogramming~5 mins

Why promises are used in Javascript - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why promises are used
O(n)
Understanding Time Complexity

We want to understand how using promises affects the time it takes for JavaScript code to run.

Specifically, we ask: How does the program's work grow when promises handle tasks?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function fetchData(urls) {
  return Promise.all(urls.map(url => fetch(url)));
}

fetchData(['url1', 'url2', 'url3']).then(results => {
  console.log(results);
});
    

This code fetches data from multiple URLs at the same time using promises.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The map function loops over each URL to start a fetch request.
  • How many times: Once for each URL in the input array.
How Execution Grows With Input

Each URL causes one fetch operation to start, so the total work grows with the number of URLs.

Input Size (n)Approx. Operations
1010 fetch calls started
100100 fetch calls started
10001000 fetch calls started

Pattern observation: The number of operations grows directly with the number of URLs.

Final Time Complexity

Time Complexity: O(n)

This means the time to start all fetches grows linearly with the number of URLs.

Common Mistake

[X] Wrong: "Promises make the code run instantly, so time does not grow with input size."

[OK] Correct: Promises start tasks asynchronously but each task still takes time, so more tasks mean more total work.

Interview Connect

Understanding how promises affect time helps you explain asynchronous code performance clearly and confidently.

Self-Check

"What if we changed Promise.all to run fetches one after another instead of all at once? How would the time complexity change?"