// Simulated API: Fetch user data
function fetchUserData(userId) {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ id: userId, name: "Alice" });
}, 500);
});
}
// Simulated API: Fetch posts by user
function fetchUserPosts(userId) {
return new Promise((resolve) => {
setTimeout(() => {
resolve([
{ id: 1, title: "First Post" },
{ id: 2, title: "Second Post" }
]);
}, 500);
});
}
// Simulated API: Fetch comments for a post
function fetchPostComments(postId) {
return new Promise((resolve) => {
setTimeout(() => {
resolve([
{ id: 101, text: "Nice post!" },
{ id: 102, text: "Thanks for sharing." }
]);
}, 500);
});
}
// 🔗 Chained Promises Example
function chainWithPromises() {
console.log('🔗 Chaining promises...');
fetchUserData(123)
.then(user => {
console.log('👤 User:', user);
return fetchUserPosts(user.id);
})
.then(posts => {
console.log('📝 Posts:', posts);
if (posts.length === 0) {
throw new Error('No posts found for user');
}
return fetchPostComments(posts[0].id);
})
.then(comments => {
console.log('💬 Comments:', comments);
})
.catch(error => {
console.error('❌ Error in chain:', error.message);
})
.finally(() => {
console.log('✅ Chain completed');
});
}
// Run both examples
chainWithPromises();
output:
No comments:
Post a Comment