0
0
Node.jsframework~30 mins

Promises for cleaner async in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Promises for cleaner async
📖 Scenario: You are building a small Node.js app that fetches user data and their posts from a server. Instead of using nested callbacks, you want to use Promises to keep your code clean and easy to read.
🎯 Goal: Build a simple Node.js script that uses Promises to fetch user data and posts asynchronously, then logs the combined result.
📋 What You'll Learn
Create a function that returns a Promise resolving user data
Create a function that returns a Promise resolving posts data
Use a configuration variable to simulate a delay time
Chain Promises to fetch user data first, then posts
Log the combined user and posts data after both Promises resolve
💡 Why This Matters
🌍 Real World
Using Promises is common in Node.js apps to handle asynchronous tasks like fetching data from APIs or databases without blocking the program.
💼 Career
Understanding Promises is essential for backend developers working with Node.js to write clean, maintainable asynchronous code.
Progress0 / 4 steps
1
Create user data fetch function
Create a function called fetchUser that returns a Promise resolving to the object { id: 1, name: 'Alice' } after a delay of 100 milliseconds.
Node.js
Need a hint?

Use new Promise and setTimeout to simulate async fetching.

2
Add delay configuration variable
Create a constant called delay and set it to 150 to use as the delay time for fetching posts.
Node.js
Need a hint?

Use const delay = 150; to set the delay time.

3
Create posts data fetch function using delay
Create a function called fetchPosts that returns a Promise resolving to the array [{ id: 101, title: 'Post 1' }, { id: 102, title: 'Post 2' }] after a delay using the delay constant.
Node.js
Need a hint?

Use the delay constant inside setTimeout for the posts fetch delay.

4
Chain Promises and log combined data
Use fetchUser() and chain it with fetchPosts() using .then(). Inside the second .then(), log an object with keys user and posts containing the resolved data.
Node.js
Need a hint?

Chain fetchUser() and fetchPosts() with .then() and combine results in an object.