【问题标题】:UnhandledPromiseRejectionWarning: ReferenceError: verifyItemInStock is not definedUnhandledPromiseRejectionWarning: ReferenceError: verifyItemInStock 未定义
【发布时间】:2020-02-10 09:16:13
【问题描述】:

我正在尝试创建一个辅助方法以在同一个控制器中使用:

module.exports = {

  async update(req, res) {

    // code here...

    // method call
    this.verifyItemInStock()

    // more code here ...

  },

  // method declaration
  verifyItemInStock (itemId) {
      // more code...
  }

}

但我收到以下错误:

(node:31904) UnhandledPromiseRejectionWarning: ReferenceError: verifyItemInStock 未定义 更新时(/home/netogerbi/workspaces/zombieresistance/zombieresistance/app/controllers/trade.controller.js:34:5) (节点:31904)UnhandledPromiseRejectionWarning:未处理的承诺 拒绝。此错误源于在异步内部抛出 没有 catch 块的函数,或者通过拒绝一个承诺 不使用 .catch() 处理。 (拒绝 ID:1)(节点:31904)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。在 未来,未处理的承诺拒绝将终止 具有非零退出代码的 Node.js 进程。

【问题讨论】:

  • 这对我有用。你能添加解释你如何使用它的代码吗?

标签: javascript node.js express


【解决方案1】:

删除this 使其更具可读性:

// method declaration
const verifyItemInStock = itemId => {
  // more code...
}

const update = async (req, res) => {
  // code here...
  // method call
  verifyItemInStock()
  // more code here ...
}


module.exports = {
  update,
  verifyItemInStock,
}

另外,promise 的消费者应该有一个陷阱:

import { update } from './my-module';

update(req, res).then(...).catch(...)
// or
try {
  const resolved = await update(req, res);
  // consume the resolved value
} catch (e) {
  // exception handling
}

【讨论】:

    【解决方案2】:

    我通过以下方式解决:

    const update = async (req, res) => {
    
      // auxiliar method declaration
      verifyItemInStock = itemId => {
          // code...
      }
    
      // ...
      // method call
      const hasItems = verifyItemInStock(id)
    
    }
    

    非常感谢...

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 1970-01-01
      • 2021-03-26
      • 2012-08-24
      • 2015-10-04
      • 2017-04-10
      • 1970-01-01
      相关资源
      最近更新 更多