【发布时间】:2021-11-17 14:16:59
【问题描述】:
假设我想运行条件为异步函数的 if 语句。
const con = require('./con');
if(con.con('email@gmail.com')
console.log('User exists!')
else {
console.log('user does not exist?')
}
这是一个函数,它使用了mongoose findOne,它是一个异步任务。
const User = require ('../nodeDB/models/user.js');
const con = function (email) {
User.findOne( { userEmail: email }, function (err, doc) {
if(err) {
console.log(err);
}
if (doc) {
return false;
} else {
return true;
}
});
}
module.exports.con = con;
问题是 if 语句在 con 执行之前被调用,然后不设置条件。
【问题讨论】:
-
你在使用 async/await 吗?
-
使用 await,或者在调用函数后将 if 放入 'then' 块中。
-
尝试添加 async 和 await 但随后它给出了错误
MongooseError: Query was already executed: User.findOne({ userEmail: 'email@gmail.com' })havent 尝试将 if 放在 then 块中,但你的意思是 if。也感谢您的回复。
标签: javascript node.js mongoose