📖 Scenario: You are building a simple web app that fetches user data from a server. Sometimes the server might fail or the data might not be available. You want to handle these errors gracefully so the app does not crash and shows a friendly message.
🎯 Goal: Learn how to use async and await to fetch data and handle errors using try and catch blocks in JavaScript.
📋 What You'll Learn
Create an async function to simulate fetching user data
Add a variable to simulate success or failure
Use try and catch inside the async function to handle errors
Print the result or error message
💡 Why This Matters
🌍 Real World
Handling errors when fetching data from servers is common in web apps to avoid crashes and show friendly messages.
💼 Career
Knowing async error handling is essential for frontend and backend developers working with APIs and asynchronous code.
Progress0 / 4 steps
1
Create an async function to fetch user data
Write an async function called fetchUserData that returns a resolved promise with the string 'User data loaded'.
Javascript
Hint
Use the async keyword before the function name and return a string directly.
2
Add a variable to simulate success or failure
Inside the fetchUserData function, create a variable called success and set it to false to simulate a failure scenario.
Javascript
Hint
Use const success = false; inside the function.
3
Use try and catch to handle errors
Modify the fetchUserData function to use a try block. Inside try, if success is false, throw a new Error with the message 'Failed to load user data'. Otherwise, return 'User data loaded'. Add a catch block that returns the error message.
Javascript
Hint
Use try { if (!success) throw new Error(...); return ...; } catch (error) { return error.message; }
4
Call the async function and print the result
Write code to call fetchUserData() using await inside an async function called main. Then print the result using console.log. Finally, call the main function.
Javascript
Hint
Wrap the call in an async main function, use await, then print the result.
Practice
(1/5)
1. What is the main purpose of using try...catch with async and await in JavaScript?
easy
A. To handle errors that occur during asynchronous operations
B. To make the code run faster
C. To convert asynchronous code into synchronous code
D. To declare variables inside async functions
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 A
Quick Check:
Error handling = To handle errors that occur during asynchronous operations [OK]
Hint: Use try...catch around await to catch async errors [OK]
Common Mistakes:
Thinking async/await makes code synchronous
Ignoring errors from awaited promises
Using try...catch without async functions
2. Which of the following is the correct syntax to catch errors from an async function using await?
easy
A. try await asyncFunc() catch error { console.log(error); }
Hint: Always include error parameter in catch(e) [OK]
Common Mistakes:
Omitting error parameter in catch
Thinking fetch is synchronous
Removing async keyword by mistake
5. You want to fetch user data and then fetch posts for that user. If either fetch fails, you want to log the error and continue without stopping the program. Which code correctly handles errors using async/await?
hard
A. async function getUserAndPosts() {
try {
const user = await fetch('/user');
const posts = await fetch(`/posts?userId=${user.id}`);
} catch (e) {
console.log('Error:', e);
}
}
B. 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));
}