0

I have a list of posts containing userId. When fetching n no.of post, I want to loop throught and get and fetch user data and append them into the post.

But before the loop gets resolved, the function gets return with undefined. After that, the post data gets listed but I want the post data to be fetched first.

I am new to promises and async. If there are any other solutions that I can use, then please notify me.

I am using sailsjs.

fetchPosts: async (req, res) => {

let feeds = [];

posts = await Posts.find({
  skip: offset,
  limit: limit,
  sort: sort,
});
if (posts) {
  /**
   * LOOPING THROUGH FETCHED POST LOOP TO GET
   * USER DATA, LIKE, SHARE, FOLLOW, BOOKMARKS
   */

  const functionWithPromise = (post) => {
    //a function that returns a promise

    console.log(feeds);
    return Promise.resolve(post);
  };

  const anotherAsyncFunction = async (post) => {
    return functionWithPromise(post);
  };

  const getUser = async (userId, post) => {
    return new Promise(async (resolve, reject) => {
      const user = await Account.findOne({ id: userId });
      if (user) {
        post = {
          ...post,
          user: {
            id: user.id,
            uName: user.uName,
            provider: user.provider,
            dpURL: user.dpURL,
            provider: user.provider,
          },
        };

        resolve(post);
      } else {
        reject(null);
      }
    });
  };

  const anAsyncFunction = async (post) => {
    if (post.isAdminPost) {
      post = {
        ...post,
        user: {
          id: "5f3b8bf00dc3f12414b7f773", // this is usedid of admin@dopaminetalks.com in `Admin` model
          uName: "DTOfficial",
          provider: "LOCAL",
          dpURL: "/dpURL/86a73b80-babc-4caa-a84c-762f6e9c1b36.png",
        },
      };
      feeds = [...feeds, post];
      return anotherAsyncFunction(feeds);
    } else {
      getUser(post.userId, post).then((post) => {
        feeds = [...feeds, post];

        return anotherAsyncFunction(feeds);
      });
    }
  };

  const getData = async () => {
    return Promise.all(posts.map((post) => anAsyncFunction(post)));
  };

  getData().then((data) => {
    console.log(data);
    return res.json({
      status: true,
      msg: "Posts Fetched",
      data: data,
    });
  });
}
},
Roamer-1888
  • 19,138
  • 5
  • 33
  • 44
Sudhakar Behera
  • 91
  • 2
  • 10
  • 1
    The else clause in `anAsyncFunction()` is missing a `return`. – Roamer-1888 Oct 07 '20 at 14:53
  • there is a return to anotherAsyncFunction(feeds) – Sudhakar Behera Oct 07 '20 at 16:42
  • There's a return inside the `.then()` but the promise returned by the whole `getUser(....).then(....)` expression needs to be returned, otherwise `anAsyncFunction()` returns `undefined` whenever it hits that `else` clause. Hence the behaviour you describe. – Roamer-1888 Oct 07 '20 at 21:14
  • You can write `return getUser(post.userId, post).then(post => functionWithPromise([...feeds, post]));` – Roamer-1888 Oct 07 '20 at 23:08
  • [Never pass an `async function` as the executor to `new Promise`](https://stackoverflow.com/q/43036229/1048572)! – Bergi Oct 08 '20 at 16:41

0 Answers0