Promise error handling in Javascript - Time & Space 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?
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 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.
As we add more promises, the time to handle all of them grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Wait for 10 promises |
| 100 | Wait for 100 promises |
| 1000 | Wait for 1000 promises |
Pattern observation: The time grows linearly as the number of promises increases.
Time Complexity: O(n)
This means the time to handle errors grows in a straight line with the number of promises.
[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.
Understanding how promise error handling scales helps you write better asynchronous code and explain your reasoning clearly in interviews.
"What if we used Promise.race instead of Promise.all? How would the time complexity change?"