繁体   English   中英

函数返回一个未定义的值

[英]Function returns a undefined value

我有一些我不明白的东西。 我尝试使用猫鼬模型从数据库中获取一些数据。 这是代码:

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) {
      // ...

我的dot函数获取值,当我在exec回调中使用console.log ,我有一个完整的对象(结果)。

但是,当我尝试从verify函数访问对象的属性时,我有一个undefined 例如,当我想记录result.hostresult.tempHash我将拥有我的值,而不是undefined

您的dot方法不返回任何内容,这就是为什么您的结果未定义的原因。

首先使dot方法返回结果:

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

现在,该dot返回一个Promise您只需调用该方法,然后等待结果:

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);
}

您正在使用异步过程,猫鼬模型是异步执行的,即,它们返回的Promise将在以后而不是立即执行。 要了解有关JavaScript异步编程的更多信息,可以查看此MDN异步发布保证

以下代码将完成您要实现的目标:

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");
    }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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