2

Everytime I send back timelinePosts I get undefined. I understand that the forEach finishes faster than the promise executes but how can I fix this? I have tried putting a function inside the forEach and have it execute the second promise but it doesn't work.

  getTimelinePosts: (req, res, next) => {
    const db = req.app.get("db");

    const { userID } = req.params;
    let timelinePosts = [];

    db.getFollowing([userID]).then(friends => {
      friends.forEach((val, i, arr) => {
        db.getTimelinePosts([val.friend_id]).then(post => {
          timelinePosts.push(post);
        });
      });
      res.status(200).send(timelinePosts);
    });
  }
PBandJ333
  • 202
  • 5
  • 15

1 Answers1

4

Map each getTimelinePosts call to a Promise and then call Promise.all on the resulting array of Promises. If you want getTimelinePosts to return a Promise as well, then return the whole Promise chain as well:

return db.getFollowing([userID]).then(friends => {
  return Promise.all(friends.map(({ friend_id }) => db.getTimelinePosts(friend_id)));
})
.then(timelinePosts => {
  res.status(200).send(timelinePosts);
  // If you want `getTimelinePosts` to return a Promise that resolves with the result:
  return timelinePosts;
});
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320