0

My react component componentWillMount() makes an axios call sending an array of objects. My node/express API gets the request. I want to map over the array sent, finding that users username with a mongoDB call to my User collection. I want to then create a new attribute in the object called username and set it to the result. I need to wait for my map function to finish before I sent my new mapped array back to the front end. I'm using async await and Promise.all(). My front end is receiving back an array of null objects.

I've tried just using regular promises, but had no luck there either. I understand the concept of async await by using the key term async on your method and basically waiting for whatever you use await on to move forward. Maybe I have that explanation wrong, just can't seem to figure it out. Quite new to async/await and promises.

exports.getAuthorUserNames = async (req, res) => {
  if (req.body.data) {
    let mappedArr = req.body.data.map(nade => {
      User.findOne({ _id: nade.authorID }, function(err, result) {
        if (err) {
          res.sendStatus(500);
        } else {
          nade.username = result.username;
        }
      });
    });
    res.status(200).send(await Promise.all(mappedArr));
  }
};

I except the result to return an array of objects with a new attribute called username with the username obtained from result.username(db call). I am receiving an array of nulls.

  • Possible duplicate of [How do I convert an existing callback API to promises?](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) – CertainPerformance Aug 08 '19 at 01:36
  • 1
    Your `.map` callback is not returning anything. Either use the `findOne` as a Promise instead of a callback, or convert it to a Promise, and `return` each Promise – CertainPerformance Aug 08 '19 at 01:36

2 Answers2

1
exports.getAuthorUserNames = async (req, res) => {
try{
  if (req.body.data) {
    const mappedArr = req.body.data.map(nade => User.findOne({ _id: nade.authorID }));
    const results = await Promise.all(mappedArr);
    return res.status(200).send(results);
  }
} catch(e){
//handle exception here
 }
};
Naresh
  • 941
  • 9
  • 22
-1
exports.getAuthorUserNames = async (req, res) => {
  if (req.body.data) {
    let mappedArr = req.body.data.map(async nade => {
      await User.findOne({ _id: nade.authorID }).then(result => {
        nade.author = result.username;
      });
      return nade;
    });
    res.status(200).send(await Promise.all(mappedArr));
  }
};