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?"
Practice
.catch() method when working with JavaScript Promises?Solution
Step 1: Understand the role of
The.catch()in Promises.catch()method is designed to handle errors or rejected promises in asynchronous code.Step 2: Differentiate from other methods
.then()handles successful resolution, while.catch()specifically catches errors.Final Answer:
To handle errors or rejected promises -> Option BQuick Check:
.catch()handles errors [OK]
- Confusing .catch() with .then()
- Thinking .catch() cancels promises
- Believing .catch() creates new promises
myPromise?Solution
Step 1: Identify the correct method for error handling
The correct method to catch errors from a promise is.catch().Step 2: Check the syntax correctness
The syntaxmyPromise.catch(error => console.log(error));correctly attaches an error handler.Final Answer:
myPromise.catch(error => console.log(error)); -> Option AQuick Check:
Use .catch() for errors [OK]
- Using .then() to catch errors
- Using non-existent methods like .error()
- Incorrect arrow function syntax
const p = new Promise((resolve, reject) => {
reject('Failed');
});
p.then(result => console.log('Success:', result))
.catch(error => console.log('Error:', error));Solution
Step 1: Analyze the promise rejection
The promise immediately rejects with the message 'Failed'.Step 2: Trace the .then() and .catch() handlers
The.then()is skipped because the promise is rejected;.catch()runs and logs 'Error: Failed'.Final Answer:
Error: Failed -> Option DQuick Check:
Rejected promise triggers .catch() [OK]
- Expecting .then() to run on rejection
- Thinking no output occurs on rejection
- Confusing reject with resolve
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log('Error:', error));
// What is wrong here?Solution
Step 1: Review the promise chain syntax
The code correctly chains.then()to parse JSON and then log data.Step 2: Confirm error handling
The.catch()properly handles any errors from fetch or JSON parsing.Final Answer:
No error, code is correct -> Option CQuick Check:
Proper chaining with .catch() [OK]
- Thinking .then() needs explicit return (arrow with braces)
- Using .error() instead of .catch()
- Believing fetch is not promise-based
fetch('https://api.example.com/data')
.then(response => response.json())
.catch(error => {
console.log('Error:', error);
return {};
})
.then(data => console.log('Data:', data));Solution
Step 1: Understand the error handling flow
The.catch()catches any errors from the fetch or JSON parsing.Step 2: Analyze the return inside .catch()
Returning an empty object{}allows the next.then()to receive a value and continue processing.Final Answer:
This pattern catches errors and returns a default value to continue processing -> Option AQuick Check:
Return in .catch() continues chain [OK]
- Assuming .catch() stops the chain without return
- Not returning a value inside .catch()
- Thinking .catch() after .then() won't catch errors
Ready to prove it?
Pass the test and this pattern moves unknown
