Error handling with async and await in Javascript - Time & Space Complexity
When using async and await, it's important to know how error handling affects the program's speed.
We want to see how the time to catch errors changes as the input or tasks grow.
Analyze the time complexity of the following code snippet.
async function fetchData(urls) {
const results = [];
for (const url of urls) {
try {
const response = await fetch(url);
const data = await response.json();
results.push(data);
} catch (error) {
results.push(null);
}
}
return results;
}
This code fetches data from multiple URLs one by one, handling errors for each fetch.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that fetches each URL sequentially.
- How many times: Once for each URL in the input array.
Each URL adds one fetch and error check, so the total work grows directly with the number of URLs.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 fetches and error checks |
| 100 | About 100 fetches and error checks |
| 1000 | About 1000 fetches and error checks |
Pattern observation: The work increases evenly as the number of URLs increases.
Time Complexity: O(n)
This means the time to complete grows in a straight line with the number of URLs to fetch.
[X] Wrong: "Using try-catch inside the loop makes the code slower exponentially."
[OK] Correct: The try-catch only adds a small fixed cost per iteration, so it grows linearly, not exponentially.
Understanding how async error handling scales helps you write reliable code that performs well as tasks increase.
"What if we fetched all URLs in parallel using Promise.all with try-catch? How would the time complexity change?"