简体   繁体   中英

Function returns a undefined value

I have something that I don't understand. I try to fetch some data from my database using a mongoose model. Here is the code:

function dot(property) {
  const result = Temp.findOne({tempHash: property}).exec( (er,result) =>  result);
}

function verify(req,res,next) {
 console.log(dot(req.query.id), dot(req.query.id));

 if (req.get('host') == dot(req.query.id).host) {
    console.log("Domain is matched. Information is from Authentic email");

    if(req.query.id == dot(req.query.id).tempHash) {
      // ...

My dot function fetch the values, when I use the console.log inside the exec callback I have a full object (result).

But when I try to access the object' properties from the verify function I have an undefined . For example when I want to log the result.host or result.tempHash I would have my value, not an undefined .

Your dot method does not return anything, that's why your result is undefined .

Start by making the dot method returns the result:

async function dot(property) {
  return Temp.findOne({ tempHash: property });
}

Now that dot returns a Promise you just have to call the method and then wait for the result:

function verify(req, res, next) {
  dot(req.query.id)
    .then(result => {
      if (!result) return;

      if (req.get('host') === result.host) {
        console.log("Domain is matched. Information is from Authentic email");
        if (req.query.id === result.tempHash) { // this condition is useless
          // ...
        }
      }
    })
    .catch(next);
}

You are working with asynchronous process, mongoose models executes asynchronously, ie, they return promises that executes later and not instantly. to find more about JavaScript asynchronous programming, you can check out this MDN async post and promises

The following code would do what you are trying to achieve: .

const dot = function(property) {
    return Temp.findOne({tempHash: property}).exec();
};

const verify = async function(req, res, next) {
    //note that result can be null when no match exists in the db
    const result = await dot(req.query.id);
    if (result && req.get('host') == result.host) {
        console.log("Domain is matched. Information is from Authentic email");
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM