Messy function #2

by jacobwsmith

JavaScript

// async function getPostsWithComments(userId) {
//   const posts = fetch(
//     `https://jsonplaceholder.typicode.com/posts?userId=${userId}`,
//   )
//     .then((res) => res.json())
//     .catch((err) => console.log("Error fetching posts", err));
//   const comments = await fetch(
//     `https://jsonplaceholder.typicode.com/comments`,
//   ).then((res) => res.json());
//   let userPosts = [];
//   for (let i = 0; i < posts.length; i++) {
//     const post = posts[i];
//     const postComments = [];
//     for (let j = 0; j < comments.length; j++) {
//       if (comments[j].postId == post.id) {
//         postComments.push(comments[j]);
//       }
//     }
//     post.comments = postComments;
//     userPosts.push(post);
//   }
//   return userPosts;
// }

async function getPostsWithComments(userId) {
  const [postRes, commentRes] = await Promise.all([
    fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`),
    fetch('https://jsonplaceholder.typicode.com/comments')
  ]);
  if(!postRes.ok || !commentRes.ok) throw new Error('Network response not ok');
  const [posts, comments] = await Promise.all([postRes.json(), commentRes.json()]);
  const commentsByPost = comments.reduce((acc, c) => {
    if(!acc[c.postId]) {
      acc[c.postId] = [];
    }
    acc[c.postId].push(c);
    return acc;
  }, {})

  return posts.map(p => {
    return {
      ...p,
      comments: commentsByPost[p.id] || []
    }
  });

}

// Testing
getPostsWithComments(1).then((result) => {
  console.log(result)
})