NodeJS 返回POST请求响应后运行方法

a5g8bdjr  于 2023-03-12  发布在  Node.js
关注(0)|答案(4)|浏览(173)

我对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 
  }
qzlgjiam

qzlgjiam1#

有两个选项可以解决此问题

mlmc2os5

mlmc2os52#

如果你使用TypeORM,一个干净的方法是使用实体监听器或订阅器,这允许你运行代码“afterInsert”:https://github.com/typeorm/typeorm/blob/master/docs/listeners-and-subscribers.md

b4lqfgs4

b4lqfgs43#

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

@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;
}
xkrw2x1b

xkrw2x1b4#

其他人建议调用异步调用而不等待它。虽然这在一定程度上是可行的,但是方法中的同步代码仍然会在你响应调用者之前执行。换句话说,如果你的另一个“跟踪历史变化”的异步方法看起来像这样

async function trackHistoryChanges(item) {
  const items = item.split('original');
  const originalItem = items[0];
  const newItem = items[1];
  if (originalDoc.trim() !== newDoc.trim()) {
    const diff = originalDoc.split(newDoc).join('')
    const docId = newDoc.split('\n')[0];
    await updateDatabase(docId, diff);
  }
}

直到您的await为止的所有代码(以及可能更多)仍将被执行。
要避免这种情况,可以使用setImmediate函数。

@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 
    setImmediate(() => trackHistoryChanges(item));
  }

相关问题