0
0
Javascriptprogramming~5 mins

Then and catch methods in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Then and catch methods
O(n)
Understanding Time Complexity

When using then and catch methods with promises, it's important to understand how the time to complete grows as the number of chained operations increases.

We want to know how the number of steps affects the total time the program takes.

Scenario Under Consideration

Analyze the time complexity of chaining multiple then and catch calls.


const promise = new Promise((resolve) => resolve(1));

promise
  .then(value => value + 1)
  .then(value => value * 2)
  .then(value => console.log(value))
  .catch(error => console.error(error));
    

This code creates a promise and chains several then methods to process the result, ending with a catch to handle errors.

Identify Repeating Operations

Look for repeated steps that happen as the chain grows.

  • Primary operation: Each then or catch callback runs once per chain link.
  • How many times: The number of chained then or catch calls determines how many callbacks run in sequence.
How Execution Grows With Input

As you add more then or catch calls, the total steps increase linearly.

Number of chained calls (n)Approx. Operations
33 callbacks run in order
1010 callbacks run one after another
100100 callbacks run sequentially

Pattern observation: The total work grows directly with the number of chained calls.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete grows in a straight line as you add more then or catch methods.

Common Mistake

[X] Wrong: "Adding more then calls doesn't affect performance much because they run instantly."

[OK] Correct: Each then callback runs in order, so more calls mean more steps, which takes more time overall.

Interview Connect

Understanding how promise chains grow helps you write efficient asynchronous code and explain your reasoning clearly in interviews.

Self-Check

What if we replaced the chained then calls with parallel Promise.all? How would the time complexity change?