簡體   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