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?"
Practice
try...catch with async and await in JavaScript?Solution
Step 1: Understand async/await behavior
Async functions return promises, and await pauses execution until the promise settles.Step 2: Role of try...catch with async/await
Errors in awaited promises can be caught using try...catch to prevent program crashes.Final Answer:
To handle errors that occur during asynchronous operations -> Option AQuick Check:
Error handling = To handle errors that occur during asynchronous operations [OK]
- Thinking async/await makes code synchronous
- Ignoring errors from awaited promises
- Using try...catch without async functions
Solution
Step 1: Identify correct try...catch syntax
try...catch blocks wrap code that might throw errors; await must be inside try.Step 2: Check each option's syntax
try { await asyncFunc(); } catch (error) { console.log(error); } correctly wraps await in try and catches errors; others have syntax errors or misuse await.Final Answer:
try { await asyncFunc(); } catch (error) { console.log(error); } -> Option DQuick Check:
Correct try...catch with await = try { await asyncFunc(); } catch (error) { console.log(error); } [OK]
- Placing await outside try block
- Using incorrect try...catch syntax
- Confusing promise.catch with try...catch
async function fetchData() {
try {
let result = await Promise.reject('Failed');
console.log('Success:', result);
} catch (error) {
console.log('Error:', error);
}
}
fetchData();Solution
Step 1: Analyze Promise.reject inside try block
Promise.reject('Failed') creates a rejected promise; await pauses until rejection.Step 2: Catch block handles the rejection error
The rejection triggers catch block, printing 'Error: Failed'.Final Answer:
Error: Failed -> Option BQuick Check:
Rejected promise caught = Error: Failed [OK]
- Expecting success message on rejection
- Missing catch block causes unhandled rejection
- Confusing Promise.reject with Promise.resolve
async function load() {
try {
const data = await fetch('https://api.example.com/data');
} catch {
console.log('Fetch failed');
}
}
load();Solution
Step 1: Check catch block syntax
Catch block should have an error parameter to receive the error object.Step 2: Confirm other parts are correct
fetch returns a promise and can be awaited; async keyword is present; try can contain await.Final Answer:
Missing error parameter in catch block -> Option AQuick Check:
Catch needs error parameter = Missing error parameter in catch block [OK]
- Omitting error parameter in catch
- Thinking fetch is synchronous
- Removing async keyword by mistake
Solution
Step 1: Understand error handling for multiple awaits
Separate try...catch blocks allow handling errors individually without stopping the whole function.Step 2: Analyze each option
async function getUserAndPosts() { try { const user = await fetch('/user'); } catch (e) { console.log('User fetch error:', e); } try { const posts = await fetch(`/posts?userId=${user.id}`); } catch (e) { console.log('Posts fetch error:', e); } } uses separate try...catch for user and posts fetch, logging errors and continuing execution. async function getUserAndPosts() { try { const user = await fetch('/user'); const posts = await fetch(`/posts?userId=${user.id}`); } catch (e) { console.log('Error:', e); } } stops on first error. async function getUserAndPosts() { const user = await fetch('/user').catch(e => console.log('User fetch error:', e)); const posts = await fetch(`/posts?userId=${user.id}`).catch(e => console.log('Posts fetch error:', e)); } mixes await with .catch but can cause undefined user. async function getUserAndPosts() { const user = fetch('/user'); const posts = fetch(`/posts?userId=${user.id}`); console.log('Data fetched'); } lacks await and error handling.Final Answer:
Option C correctly handles errors separately and continues execution -> Option CQuick Check:
Separate try...catch for each await = async function getUserAndPosts() { try { const user = await fetch('/user'); } catch (e) { console.log('User fetch error:', e); } try { const posts = await fetch(`/posts?userId=${user.id}`); } catch (e) { console.log('Posts fetch error:', e); } } [OK]
- Using one try...catch for multiple awaits stopping on first error
- Mixing await with .catch causing undefined variables
- Not awaiting fetch calls
Ready to prove it?
Pass the test and this pattern moves unknown
