Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function inside async function at a js class

Hi I'm new at javascript programming.

I have a node express project, I'm trying to create a login method inside my AuthenticationController class.

My login method is like this right now:

const User = require('../models/User')

class AuthenticationController {

  async login(req, res) {
    const { email, password } = req.body
    console.log('step 1')
    var hashPassword = await userPassword(email)
    console.log(hashPassword)
    console.log('step 2')
    return res.status(200).json({ 'msg': 'Log in OK!' })

  }

  userPassword(email) {
    User.findOne({ email: email }).exec(function(err, user) {
      if (err) return err
      else return user.password
    })
  }
}

But I got an error saying that userPassword is undefined, I couldn't figure out why. So my doubts are: why this is happening, and how to do it correctly ?

I also checked out this questions, but they didn't helped me:

  • How to call an async function
  • Async function inseide a class

The error message at my console:

(node:28968) UnhandledPromiseRejectionWarning: ReferenceError: userPassword is not defined ...

(node:28968) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

(node:28968) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

like image 737
Lucas Andrade Avatar asked Jun 16 '26 12:06

Lucas Andrade


1 Answers

login doesn't refer to userPassword method but to the function of the same name which doesn't exist.

Promises are supposed to be be chained and they aren't. userPassword is expected to return a promise but it uses obsolete Mongoose callback API.

That UnhandledPromiseRejectionWarning is shown means that errors weren't correctly handled in login while they should. As explained in this answer, Express don't support promises so errors should be handled by a developer.

It should be:

  async login(req, res) {
      try {
        const { email, password } = req.body
        var hashPassword = await this.userPassword(email)
        return res.status(200).json({ 'msg': 'Log in OK!' })
      } catch (err) {
        // handle error
      }
  }

  async userPassword(email) {
    const { password } = await User.findOne({ email: email });
    return password;
  }
like image 138
Estus Flask Avatar answered Jun 19 '26 00:06

Estus Flask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!