0
0
Javascriptprogramming~5 mins

Promise error handling in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Promise error handling
O(n)
Understanding Time Complexity

We want to understand how the time it takes to handle errors in promises changes as we add more promises.

How does the number of promises affect the time to catch errors?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const promises = [promise1, promise2, promise3];

Promise.all(promises)
  .then(results => {
    console.log('All done', results);
  })
  .catch(error => {
    console.error('Error caught:', error);
  });
    

This code waits for all promises to finish and catches any error from any promise.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Waiting for each promise to settle (resolve or reject).
  • How many times: Once per promise in the array.
How Execution Grows With Input

As we add more promises, the time to handle all of them grows roughly in direct proportion.

Input Size (n)Approx. Operations
10Wait for 10 promises
100Wait for 100 promises
1000Wait for 1000 promises

Pattern observation: The time grows linearly as the number of promises increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to handle errors grows in a straight line with the number of promises.

Common Mistake

[X] Wrong: "Promise.all runs all promises instantly, so error handling is constant time."

[OK] Correct: Even though promises start together, the program must still wait for each to finish or fail, so time grows with how many promises there are.

Interview Connect

Understanding how promise error handling scales helps you write better asynchronous code and explain your reasoning clearly in interviews.

Self-Check

"What if we used Promise.race instead of Promise.all? How would the time complexity change?"