0
0
Javascriptprogramming~5 mins

Promise chaining in Javascript - Time & Space Complexity

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

When using promise chaining, we want to know how the time to complete tasks grows as we add more steps.

We ask: How does adding more chained promises affect the total time?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const promiseChain = () => {
  return new Promise(resolve => setTimeout(() => resolve(1), 1000))
    .then(result => {
      return new Promise(resolve => setTimeout(() => resolve(result + 1), 1000));
    })
    .then(result => {
      return new Promise(resolve => setTimeout(() => resolve(result + 1), 1000));
    });
};

This code creates a chain of promises where each step waits and then adds 1 to the result.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Each then callback runs one after another, waiting for the previous promise to finish.
  • How many times: The number of then steps in the chain determines how many times this happens.
How Execution Grows With Input

Each chained promise waits for the previous one, so total time adds up with each step.

Input Size (number of chained promises)Approx. Total Time (ms)
11000
22000
33000

Pattern observation: Total time grows linearly as you add more chained promises.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows directly in proportion to the number of chained promises.

Common Mistake

[X] Wrong: "All promises run at the same time, so chaining does not add time."

[OK] Correct: In chaining, each promise waits for the previous one to finish, so times add up instead of running together.

Interview Connect

Understanding how promise chains affect time helps you write efficient asynchronous code and explain your reasoning clearly.

Self-Check

What if we changed the chained promises to run in parallel using Promise.all? How would the time complexity change?