【问题标题】:NodeJS return the boolean value instead of promise pendingNodeJS返回布尔值而不是promise挂起
【发布时间】:2020-08-17 19:21:23
【问题描述】:

我需要从下面代码的第二个函数返回一个布尔值。然而,返回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
}

【问题讨论】:

  • 这能回答你的问题吗? return value after a promise
  • 所有 async 函数都返回一个承诺 - 总是。这就是 JavaScript 语言中 async 函数的工作方式。 async 函数的调用者必须使用 .then()await 从该承诺中获取返回值。您不能从 async 函数返回纯值。

标签: node.js promise es6-promise


【解决方案1】:

这个用例是完全错误的。

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

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

【讨论】:

    猜你喜欢
    • 2021-02-20
    • 1970-01-01
    • 2017-06-02
    • 2017-04-22
    • 2020-02-13
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多