Skip to content

Commit fade56d

Browse files
committed
fix: 4b303be9-ab82-4678-a37c-032d3ee14807
1 parent 10e2728 commit fade56d

File tree

1 file changed

+21
-16
lines changed
  • questions/how-do-you-handle-errors-in-asynchronous-operations

1 file changed

+21
-16
lines changed

questions/how-do-you-handle-errors-in-asynchronous-operations/en-US.mdx

+21-16
Original file line numberDiff line numberDiff line change
@@ -58,28 +58,33 @@ fetchData(); // Error fetching data: ....
5858
If you have multiple asynchronous operations, you can nest `try...catch` blocks to handle errors at different levels.
5959

6060
```js live
61-
async function fetchData() {
62-
try {
63-
// Invalid URl
64-
const response = await fetch('https://api.example.com/data');
65-
const data = await response.json();
66-
console.log(data);
67-
} catch (error) {
68-
console.error('Error fetching data:', error);
69-
}
61+
async function fetchUser() {
62+
// Simulate a successful async operation
63+
return { id: 1, name: 'Alice' };
7064
}
7165

72-
async function processData() {
66+
async function fetchUserPosts() {
67+
// Simulate a failed async operation
68+
throw new Error('Failed to fetch posts');
69+
}
70+
71+
async function loadUserData() {
7372
try {
74-
await fetchData();
75-
// Additional processing
76-
console.log(arr); // Trying to reference an undefined variable will throw an error
77-
} catch (error) {
78-
console.error('Error processing data:', error);
73+
const user = await fetchUser();
74+
console.log('User:', user);
75+
76+
try {
77+
const posts = await fetchUserPosts();
78+
console.log('Posts:', posts);
79+
} catch (postsError) {
80+
console.error('Error fetching posts:', postsError.message);
81+
}
82+
} catch (userError) {
83+
console.error('Error fetching user:', userError.message);
7984
}
8085
}
8186

82-
processData();
87+
loadUserData();
8388
```
8489

8590
## Using `.catch()` with Promises

0 commit comments

Comments
 (0)