[英]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). 我的dot
函数获取值,当我在exec
回调中使用console.log
,我有一个完整的对象(结果)。
But when I try to access the object' properties from the verify
function I have an undefined . 但是,当我尝试从verify
函数访问对象的属性时,我有一个undefined 。 For example when I want to log the result.host
or result.tempHash
I would have my value, not an undefined . 例如,当我想记录result.host
或result.tempHash
我将拥有我的值,而不是undefined 。
Your dot
method does not return anything, that's why your result is undefined . 您的dot
方法不返回任何内容,这就是为什么您的结果未定义的原因。
Start by making the dot
method returns the result: 首先使dot
方法返回结果:
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: 现在,该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);
}
You are working with asynchronous process, mongoose models executes asynchronously, ie, they return promises that executes later and not instantly. 您正在使用异步过程,猫鼬模型是异步执行的,即,它们返回的Promise将在以后而不是立即执行。 to find more about JavaScript asynchronous programming, you can check out this MDN async post and promises 要了解有关JavaScript异步编程的更多信息,可以查看此MDN异步发布并保证
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");
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.