0
0
Node.jsframework~30 mins

Promise catch for async errors in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling Async Errors with Promise.catch in Node.js
📖 Scenario: You are building a simple Node.js app that fetches user data from a fake API. Sometimes the API might fail, so you need to handle errors properly.
🎯 Goal: Learn how to use Promise.catch to catch errors from asynchronous operations and handle them gracefully.
📋 What You'll Learn
Create a function that returns a Promise simulating an API call
Create a variable to hold the user ID to fetch
Call the function with the user ID and handle success and error using then and catch
Log the user data on success and log the error message on failure
💡 Why This Matters
🌍 Real World
Handling errors in asynchronous operations like API calls is essential in real-world Node.js applications to avoid crashes and provide good user experience.
💼 Career
Understanding Promise error handling is a fundamental skill for backend developers working with Node.js and asynchronous JavaScript.
Progress0 / 4 steps
1
Create a function that returns a Promise simulating an API call
Create a function called fetchUserData that takes a parameter userId and returns a new Promise. Inside the Promise, use setTimeout to simulate a delay of 100 milliseconds. If userId is 1, resolve the Promise with the object { id: 1, name: 'Alice' }. Otherwise, reject the Promise with an Error with the message 'User not found'.
Node.js
Need a hint?

Use new Promise and setTimeout to simulate async behavior. Use resolve and reject inside the timeout.

2
Create a variable to hold the user ID to fetch
Create a variable called userId and set it to the number 2.
Node.js
Need a hint?

Use const userId = 2; to set the user ID.

3
Call the function and handle success and error using then and catch
Call fetchUserData with the variable userId. Use then to receive the user data and log it with console.log. Use catch to catch any error and log the error message with console.log.
Node.js
Need a hint?

Use fetchUserData(userId).then(...).catch(...) to handle success and errors.

4
Change the user ID to 1 and verify success handling
Change the value of the variable userId to 1 to simulate a successful API call.
Node.js
Need a hint?

Simply change const userId = 2; to const userId = 1;.