我只是在为后端做一个获取路由,而当我进行console.log记录时,我无法弄清楚为什么变量user和pass仍然为false。除了findOne之外,还有其他方法/功能可以检查用户名和密码是否正确吗?
app.get('/connect', (req, res) => {
let user = false;
let pass = false;
User.findOne({login: req.query.login}).then((currentUser) => {
if (currentUser)
user = true;
})
User.findOne({password: req.query.password}).then((currentPassword) => {
if (currentPassword)
pass = true;
})
console.log(user); //prints still false
console.log(pass); //prints still false
});
答案 0 :(得分:3)
似乎等待着解决。
如上所述,由于异步特性,它将触发这些请求并立即继续进行。这就是为什么您的控制台将打印为false的原因,但是实际上在N次之后,它们已被更改。
您可以通过以下方式将功能设置为异步:
async (a,b) => {}
(如果您使用速记)。然后,您可以说:await functioncall();
用于需要处理的蚂蚁异步调用。
请记住,如果您要等待某事,则父函数需要异步。多数民众赞成在这里带走。
将所有内容组合在一起,如下所示:
app.get('/connect', async (req, res) => { // If you leverage await, you need to define parent function as async by a keyword.
let user = false;
let pass = false;
//you tell this function to wait until it has fully finished its promise chain.
await User.findOne({login: req.query.login}).then((currentUser) => {
if (currentUser)
user = true;
})
// Same as above
await User.findOne({password: req.query.password}).then((currentPassword) => {
if (currentPassword)
pass = true;
})
console.log(user); //now will print true.
console.log(pass); //now will print true.
});
我注意到上面的主要更改。
答案 1 :(得分:1)
您需要使数据库搜索异步。您可以使用async / await来完成该操作。
app.get('/connect', async (req, res) => {
let user = false;
let pass = false;
const currentUser = await User.findOne({login: req.query.login});
if (currentUser)
user = true;
const currentPassword = await User.findOne({password: req.query.password});
if (currentPassword)
pass = true;
console.log(user);
console.log(pass);
});