-1

I need to return a boolean value from the second function of my code below. However, returning isValidOrg gives me Promise { <pending> } while console.logging the variable gives me the answer I need. Is there any possibility to return 0 or 1 in my case?

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
}
DevWannabe
  • 87
  • 1
  • 7
  • Does this answer your question? [return value after a promise](https://stackoverflow.com/questions/22951208/return-value-after-a-promise) – jonrsharpe Aug 17 '20 at 10:44
  • 2
    ALL `async` functions return a promise - always. That's how `async` functions in the Javascript language work. The caller of an `async` function must use `.then()` or `await` to get the return value out of that promise. You cannot return a plain value from an `async` function. – jfriend00 Aug 17 '20 at 14:06

1 Answers1

1

This usecase is entirely wrong.

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

Why are you chaining .then, just simply assign it to isValidOrg and evaluate it in the next line.

Mahad Ansar
  • 176
  • 3