[英]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.host
或result.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.