Promise chaining in Javascript - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: Each
thencallback runs one after another, waiting for the previous promise to finish. - How many times: The number of
thensteps in the chain determines how many times this happens.
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) |
|---|---|
| 1 | 1000 |
| 2 | 2000 |
| 3 | 3000 |
Pattern observation: Total time grows linearly as you add more chained promises.
Time Complexity: O(n)
This means the total time grows directly in proportion to the number of chained promises.
[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.
Understanding how promise chains affect time helps you write efficient asynchronous code and explain your reasoning clearly.
What if we changed the chained promises to run in parallel using Promise.all? How would the time complexity change?