在 js 类的异步函数中调用函数

Luc*_*ade 3 javascript mongoose node.js express async-await

嗨,我是 javascript 编程的新手。

我有一个 node express 项目,我试图在我的 AuthenticationController 类中创建一个登录方法。

我现在的登录方法是这样的:

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
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

但是我收到一条错误消息,说 userPassword 未定义,我不知道为什么。所以我的疑问是:为什么会发生这种情况,以及如何正确地做到这一点?

我也检查了这个问题,但他们没有帮助我:

我的控制台上的错误消息:

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

(node:28968) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这个错误要么是因为在没有 catch 块的情况下抛出了异步函数,要么是因为拒绝了一个没有用 .catch() 处理过的承诺。(拒绝编号:1)

(节点:28968)[DEP0018] 弃用警告:不推荐使用未处理的承诺拒绝。将来,未处理的承诺拒绝将使用非零退出代码终止 Node.js 进程。

Est*_*ask 6

login不是指userPassword方法,而是指不存在的同名函数。

Promise 应该被链接起来,但它们不是。userPassword预计会返回一个承诺,但它使用过时的 Mongoose 回调 API。

UnhandledPromiseRejectionWarning表明错误在login应该处理的时候没有被正确处理。正如这个答案中所解释的,Express 不支持 promise,因此错误应该由开发人员处理。

它应该是:

  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;
  }
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的答案,但要回答为什么 userPassword 未定义的问题,您在类中调用了一个不存在的函数。添加“this”后,您现在引用的是类的方法。 (2认同)