【问题标题】:nestjs is there a difference with or without async/await?nestjs 有或没有 async/await 有区别吗?
【发布时间】:2020-12-27 23:17:04
【问题描述】:

我认为以下之间没有区别:

@Post()
saveClient(@Param() params, @Body() createClientDto: ClientDto) {
   this.clientRepository.save(createClientDto);
  }

@Post()
  async saveClient(@Param() params, @Body() createClientDto: ClientDto) {
   await this.clientRepository.save(createClientDto);
  }

但是如果没有 async/await,函数会返回 void,如果发生异常,我会得到:

(node:62777) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。在未处理的承诺拒绝时终止节点进程。 (节点:62827)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。 未来,未处理的 Promise 拒绝将终止 Node.js 进程并使用非零退出代码。

使用 async/await 不会显示上述警告,因为该函数返回一个 Promise。 如果我添加一个 return 也是一样的:

@Post()
saveClient(@Param() params, @Body() createClientDto: ClientDto) {
   return this.clientRepository.save(createClientDto);
  }

所以我有点担心:一个简单的丢失return 可能会终止我的nestjs 进程?

谢谢

【问题讨论】:

  • 是的。在您的第一个示例中未能返回承诺意味着当该操作出现错误时没有人会注意,因为没有本地 .catch() 所以调用者处理错误的唯一方法是让您返回它。这是一个基本的 Promise 编程错误,既没有返回 Promise,所以调用者可以处理错误或使用 .catch() 在本地处理错误。
  • 我建议使用'@typescript-eslint/no-floating-promises': 'error'。 NestJs 处理(或此处的 NodeJS)是正确的 - 如果您不想将其返回给 API 客户端,则需要等待。否则使用return(适用于异常过滤器)。如果您希望出现错误并且仍然向 API 客户端显示“成功”,请使用 .catch() 并在那里处理它。

标签: node.js promise async-await nestjs


【解决方案1】:

尝试用try / catch包装它

@Post()
  async saveClient(@Param() params, @Body() createClientDto: ClientDto) {
    try {
       await this.clientRepository.save(createClientDto);
    } catch(err) {
       console.log(err);
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 2012-03-20
    • 1970-01-01
    • 2019-12-04
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多