【发布时间】:2020-10-16 06:56:14
【问题描述】:
您好,我正在调试我的应用程序但卡住了,我认为关于如何在异步函数中正确处理 mongoose,我还没有完全掌握。
所以我的主 server.js 有类似的东西
const user = await userService.authenticate({ username, password });
console.log("user in the main method is ...");
console.log(user);
我还有另一个“userService.js”,类似于(简化)
async function authenticate({ username, password }) {
await Users.find({ username: username, password: password }, function(
err,
user
) {
if (err) res.send(err);
if (user) {
console.log("user within the authenticate method is... ");
console.log(user);
return user;
}
});
}
问题出在authenticate 方法中,console.log 具有正确的身份验证信息,但是在主 server.js 中我得到了不同的值。我怀疑这与我使用 async 和 await 关键字的方式有关。这是我从控制台得到的结果
user within the authenticate method is...
[
{
_id: 5ee845ee39fdf73190068308,
username: 'XXXXXX',
firstName: 'XXX',
lastName: 'XXX',
password: 'XXX',
categoryDiscount: [ [Object], [Object] ]
}
]
user in the main method is ...
undefined
【问题讨论】:
标签: node.js mongoose promise async-await