node.js - NodeJS返回布尔值而不是promise挂起
问题描述
我需要从下面代码的第二个函数返回一个布尔值。但是,返回isValidOrg
给了我Promise { <pending> }
,而 console.logging 变量给了我需要的答案。在我的情况下是否有可能返回 0 或 1?
const GetOrganization = userId => {
return User.aggregate([
{ $match: { _id: mongoose.Types.ObjectId(userId) } },
{
$project: {
_id: 0,
organization: 1
}
}
])
}
async req => {
const token = req.headers['authorization'].substr(7);
const secret = req.headers['x-client-secret'];
const xOrg = req.headers['x-organization']
const { _id } = jwt.verify(token, secret)
const isValidOrg = await GetOrganization(_id).then(res => {
return xOrg !== res[0].organization ? 0 : 1
})
console.log(isValidOrg)
return isValidOrg // <-- This line here returns Promise { <pending> }, I need 0 or 1
}
解决方案
这个用例是完全错误的。
const isValidOrg = await GetOrganization(_id).then(res => {
return xOrg !== res[0].organization ? 0 : 1
})
为什么要链接 .then,只需将其分配给 isValidOrg 并在下一行对其进行评估。
推荐阅读
- powershell - PowerShell中的“$($var)”和(“$var”)有什么区别
- javascript - Angular:刷新浏览器页面后无法重新加载数据
- angular - 将文件从浏览器表单存储到 MinIO (Angular2)
- python - 您将如何从文本数据中识别身体部位和受伤类型?
- git - 如何检查分支是否已合并到其他分支?
- angular - 如何存储 rxjs 发出的值?
- css - 切换到移动视图时,我的某些 CSS 不起作用
- routing - 当 url 以角度 6 加载时,url 中缺少查询参数
- recursion - 如何编写一个利用长度函数递归查找并返回具有最大长度的子列表的函数
- jquery - 复制元素内的所有内容,除了其文本内容