【问题标题】:Running a Method after returning a POST request response返回 POST 请求响应后运行方法
【发布时间】:2020-05-06 19:33:23
【问题描述】:

我对 JS 很陌生,我正在使用 NestJS 和 mongo 来开发后端 api。我有一个基本的 CRUD 操作。我希望能够创建文档,将其返回给用户并运行另一个方法而不影响用户。

  @Post()
  async create(@Body() body: Dto, @Headers('id') id: string) {   
    body.id = id;    
    const item = await this.service.create(body);
    return item;

  // Now, I want to call another method async to trace history changes 
  }

【问题讨论】:

    标签: node.js asynchronous async-await controller nestjs


    【解决方案1】:

    有两种方法可以解决这个问题

    【讨论】:

    • 第二个任务只有在我创建文档后才能发生。我正在考虑做 Promise.then() 并调用我的方法,但我不希望用户等待第二个任务。
    • 那么你要么需要在那时做,要么开火然后忘记
    • 正如@AshishModi 所说,在第一个项目符号中,等待服务创建您的资源,然后使用历史跟踪调用您的方法,不要等待它(this.historyService.trace()),然后是return item .这样,您将向您的用户发送 POST 响应并触发您的历史跟踪方法。
    【解决方案2】:

    如果您使用的是 TypeORM,一种简洁的方法是使用实​​体侦听器或订阅者。这允许您运行代码“afterInsert”:https://github.com/typeorm/typeorm/blob/master/docs/listeners-and-subscribers.md

    【讨论】:

      【解决方案3】:

      您可以添加对另一个异步方法的调用

      @Post()
      async create(@Body() body: Dto, @Headers('id') id: string) {   
        body.id = id;    
        const item = await this.service.create(body);
        this.service.anotherAsyncMethod(); 
      
        return item;
      }
      

      【讨论】:

        猜你喜欢
        • 2021-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-20
        • 2020-04-28
        • 1970-01-01
        相关资源
        最近更新 更多