0
0
Node.jsframework~30 mins

Async/await syntax in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Async/Await Syntax in Node.js
📖 Scenario: You are building a simple Node.js program that fetches user data from a mock API. You want to use modern async/await syntax to handle asynchronous calls clearly and simply.
🎯 Goal: Create a function that fetches user data asynchronously using async/await syntax and logs the user's name.
📋 What You'll Learn
Create a function called fetchUser that returns a Promise resolving to an object with name and age.
Create a variable called userId with the value 42.
Create an async function called getUserName that uses await to get the user data from fetchUser.
Inside getUserName, return the name property from the fetched user object.
💡 Why This Matters
🌍 Real World
Async/await is used in Node.js to handle operations like reading files, making network requests, or querying databases without blocking the program.
💼 Career
Understanding async/await is essential for backend developers working with Node.js to write clean, readable asynchronous code.
Progress0 / 4 steps
1
Create the mock fetchUser function
Create a function called fetchUser that takes a parameter id and returns a Promise. The Promise should resolve to an object with name set to 'Alice' and age set to 30.
Node.js
Need a hint?

Use new Promise and call resolve with the user object inside.

2
Create the userId variable
Create a variable called userId and set it to the number 42.
Node.js
Need a hint?

Use const userId = 42; to create the variable.

3
Create the async getUserName function
Create an async function called getUserName that takes no parameters. Inside it, use await to call fetchUser with userId and store the result in a variable called user. Then return user.name.
Node.js
Need a hint?

Remember to mark the function with async and use await before fetchUser(userId).

4
Call getUserName and handle the result
Call getUserName() and use .then() to receive the returned name. Inside the then callback, assign the received name to a variable called userName.
Node.js
Need a hint?

Use getUserName().then((name) => { const userName = name; }) to handle the async result.