2

I'm getting the required result from console.log in getuser(), but I'm getting undefined when used it in another function

let getuser = (id) => {
  user.findById(id, (err, user) => {
    if (err || !user) {
      return "wrong user id";
    } else {
      let { name, _id } = user;
      console.log(JSON.stringify({ name, _id }));
      return { name, _id };
    }
  });
};

I'm getting undefined when i use getuser() in send()

exports.send = (req, res) => {
let {id}=req.body
let a=getuser(req.User._id)
let b=getuser(req.body.id)
console.log(a)
console.log(a)
let message = new messages({
                user1: a,
                user2: b,
              });
              message.save((err, saved) => {
                if (err) {
                  return res.json(err);
                } else {
                  return res.json(saved);
                }
              });
            } 

im getting undefined in

console.log(a) console.log(a)

ram
  • 200
  • 1
  • 11

1 Answers1

2

You probably want to use a Promise for the getuser method:

let getuser = (id) => new Promise((resolve, reject) => {
  user.findById(id, (err, user) => {
    if (err || !user) {
      reject("wrong user id");
    } else {
      let { name, _id } = user;
      console.log(JSON.stringify({ name, _id }));
      resolve({ name, _id });
    }
  });
});

The operation looks asynchronous, so you need to wait for the result before continuing. This means that your getuser calls need to handle promise/async values:

let a = await getuser(req.User._id)
let b = await getuser(req.body.id)

Of course, await must be used in a function marked with async. Read up on Promises and async/await if any of this is unclear - they're absolutely imperative for working with databases, APIs etc.. It may be possible to use it immediately by changing your exports line:

exports.send = async (req, res) => {

But I don't know what environment this is for, so I can't say if that will work out of the box.

Please note that I haven't tested this at all, as it's a rather incomplete example to begin with. What I've suggested is merely theoretical.

Perry Mitchell
  • 665
  • 6
  • 16