Promise chaining
📖 Scenario: You are building a simple Node.js program that simulates fetching user data and then fetching that user's posts from a server. Each fetch returns a Promise that resolves after a short delay.
🎯 Goal: Build a chain of Promises where you first fetch a user, then fetch the posts of that user, and finally log the posts.
📋 What You'll Learn
Create a function
fetchUser that returns a Promise resolving to the user object { id: 1, name: 'Alice' } after 100ms.Create a function
fetchPosts that takes a user ID and returns a Promise resolving to an array of posts [{ id: 1, title: 'Hello World' }, { id: 2, title: 'Learning Promises' }] after 100ms.Create a variable
userId to store the fetched user's ID.Chain the Promises so that
fetchUser is called first, then fetchPosts is called with the userId, and finally the posts are logged.💡 Why This Matters
🌍 Real World
Promise chaining is used in Node.js to handle sequences of asynchronous tasks, such as fetching data from APIs or databases in order.
💼 Career
Understanding Promise chaining is essential for backend developers working with asynchronous JavaScript, enabling them to write clean, readable, and maintainable code.
Progress0 / 4 steps