0

I'm building backend to fetch pictures of users I follow. The function below is a helper function that takes an array of user IDs to map against it to get their pictures. This function returns a single promise.

const getFeedPhotos = async (followingArr) => {        
  const promises = followingArr.map(async userId => { 
      await Photo.find({userId: mongoose.Types.ObjectId(userId)});
  });
  const x = Promise.all(promises);
  return x;
};

Code below is the router itself where I am invoking my helper function.

photoRouter.get(
    '/feed',
    expressAsyncHandler(async (req, res) => {
      const following = req.body.following;

      if (following) {
        const response = getFeedPhotos(following);
        console.log(response);
      } else {
          res.status(400).send({ message: '"Following" is not provided.' })
      }

    })
  );

The problem is that response equals to Promise { <pending> }. I need this promise to resolve in order to send it to my client. My question is how do I do that? I do realize that it has to do with some blunder of mine and stems from my misunderstanding of the whole async concept per se. I was trying to make some research but none of the solutions worked for me.

ArtemNovikov
  • 311
  • 4
  • 8
  • 1
    Since your code in the `expressAsyncHandler` callback is in an `async` function, you can use `await`: `const response = await getFeedPhotos(following);` `response` will receive an array of the fulfillment values of the array of promises that `getFeedPhotos` gave to `Promise.all` (assuming they all are fulfilled rather than any of them being rejected). – T.J. Crowder Sep 11 '21 at 16:22
  • @T.J.Crowder I did as you told but `response` is `[ undefined, undefined ]`. Although, If I am logging the value out from within `map` function I get real data from my database. I really wonder what makes it undefined. – ArtemNovikov Sep 12 '21 at 12:49
  • 1
    Your `map` callback doesn't specify any return value, so the promise is fulfilled with the value `undefined`. There's no reason for that callback to be `async`, actually. Just: `const promises = followingArr.map(userId => Photo.find({userId: mongoose.Types.ObjectId(userId)})); return Promise.all(promises);` – T.J. Crowder Sep 12 '21 at 12:53
  • 1
    @T.J. Crowder Now it works. Thank you! It was too silly of me. I'm in the very beginning of my journey but I've already noticed that the most of the problems we get stem from small but crucial details we are supposed to be aware of from the very beginning. – ArtemNovikov Sep 12 '21 at 13:06
  • 1
    I'm glad to have been able to help! Happy coding! – T.J. Crowder Sep 12 '21 at 13:12

0 Answers0