node.js - ExpressJS - 返回未定义的函数
问题描述
函数checkFamilyStatus()
由于某种原因一直返回 undefined,当它应该从 mongodb 集合返回一个布尔值时。
这里有一点上下文 - 我决定将逻辑部分与 get 和 post 方法等路由器方法分开,以使其看起来像函数式编程一样清晰易懂。所以我把逻辑部分放在函数中,并在路由器方法中调用它们,但是没有成功。此外,我不知道这是否是一个好习惯。如果这样做不是更容易阅读,而不是说,将一大堆代码放在一个地方吗?
我已经被这段代码卡住了一段时间。我对整个异步 JS 的工作感到有些困惑。我做了一些研究,但仍然不明白为什么这不起作用。有人可以为我澄清一下吗?
// post method
router.post("/create", ensureAuthenticated, async(req, res) => {
let userID = req.user.id;
console.log(await checkFamilyStatus(userID)); // but returns undefined
// rest of the code
}
// check family status
checkFamilyStatus = async userID => {
Account.findOne({
_id: userID
}, (err, account) => {
return account.hasFamily; // should return boolean value ?
});
};
解决方案
假设背后的逻辑account.hasFamily
是正确的,那么你需要await
为返回,所以它应该是return await account.hasFamily;
推荐阅读
- angular - Angular 中的浅层测试 - 覆盖模板 - 这是一种好习惯吗?
- gitlab - 即使测试失败,Gitlab runner 也不会失败构建
- api - react Native 中的动态 HTTP 标头
- iccube - 如何通过 XMLA 使用 $Monitoring 多维数据集获取用户统计信息?
- go - 无法解析 Go 代码中的值
- java - Hybris Commerce ERR SSL 版本或密码不匹配
- c++ - Clang、GCC 和 LTO 之间的互操作性
- neo4j - 如何通过对值使用聚合函数来删除节点和关系
- r - 如何在 R 中获取点-点-点参数的名称
- javascript - 每页有 7 个不同的侧面板