Thursday, September 25, 2025

PROMISES







 // 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:

 




// 🔄 Async/Await Flow
async function chainWithPromises(userId) {
  try {
  console.log('🔗 Chaining promises...');
    const user = await fetchUserData(userId);
    console.log("👤 User:", user);
   // console.log("📄 Fetching posts...");
    const posts = await fetchUserPosts(user.id);
    console.log("📝 Posts:", posts);
    if (posts.length === 0) throw new Error("No posts found");
   // console.log("💬 Fetching comments...");
    const comments = await fetchPostComments(posts[0].id);
    console.log("💬 Comments:", comments);
  } catch (error) {
    console.error("❌ Error:", error.message);
  } finally {
      console.log('✅ Chain completed');
  }
}

// Run the flow
chainWithPromises(123);