首页 > 解决方案 > 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
}

标签: node.jspromisees6-promise

解决方案


这个用例是完全错误的。

const isValidOrg = await GetOrganization(_id).then(res => {
        return xOrg !== res[0].organization ? 0 : 1
})

为什么要链接 .then,只需将其分配给 isValidOrg 并在下一行对其进行评估。


推荐阅读