3

i have been trying to insert an object into an array in async function ,but it return an empty array as output in nodejs ,mongoose

var data = [];

app.get("/api/post", async (req, res) => {
  const post = await UserPost.find();

  post.forEach(async element => {
    const email = await element.userid;
    const user = await Account.find({ email });
    const usern = await user[0].username;

    var userobject = {
      element,
      usern
    };
    //Promise.all(userobject)
    data.push(userobject);
  });

  console.log(data);

  res.send({ data });
});

Ru Chern Chong
  • 3,692
  • 13
  • 33
  • 43
  • Possible duplicate of [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – CertainPerformance Jun 23 '19 at 07:57

1 Answers1

3

It seems you are struggling with promises. In order to achieve this specific scenario, you can use Promise.all and Array.map.

Here is a code I edited for you:

(*please note that this is just a dummy code for the sake of explanation)

app.get("/api/post", async (req, res) => {
  try {
    const posts = await dummyPromiseResolver(); // first promise

    const promises = posts.map(async element => {
      const user = await dummyEmailReturn(element.userid); // second promise
      const usern = user[0].username;
      return {
        usern,
        ...element
      };
    });

    const fresult = await Promise.all(promises);
    res.send(fresult);
  } catch (error) {
    console.error("error in posts fetch:" + error);
  }
});

If I describe this code, posts.map is creating an Array of promises since we need to iterate through every object in the array and needs to add values from separate promises.

Then Promise.all can execute your promise array and return final results array with your desired results.

Note: You can also use for … of as well but when we need to happen things parallelly we use Promise.all. You can find more information from this thread.

here is a link for code sandbox: https://codesandbox.io/embed/serverless-cookies-nu4h0

Please note that I have added dummyPromiseResolver and dummyEmailReturn which would be equal to UserPost.find() and Account.find() functions respectively. In addition to that, I removed a few unnecessary awaits in your code. I added a try catch block to catch any exceptions. You can change that try catch as you please.

hope this will help you. let me know if you need more clarifications.

Nadun
  • 7,463
  • 1
  • 21
  • 27