node.js - 返回 POST 请求响应后运行方法
问题描述
我对 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
}
解决方案
有两个选项可以解决此选项
Fire and forget - 在不等待的情况下调用异步操作,然后将其返回给用户。这样您的电话将被接听,但节点不会等待响应的到来。
第二种方法是并行执行以减少处理两个请求所需的时间。您可以
Promise.all
并行使用和做两件事。这是推荐的方式。请参阅此处的示例 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
推荐阅读
- google-chrome - 获取自定义 buildpack google-chrome heroku 时出错
- c# - 无效的符号种类:NamedType
- c# - 如何在不使用js的情况下将html或xml转换为图片格式
- bash - 使用 bash 命令将驼峰大小写转换为小写和下划线大小写
- python - 评估张量标量提高 ValueError Tensorflow
- c# - 如何将 listviewitem 绑定到 Listview?
- r - 你能解释一下下面的R代码吗?
- jquery - JQuery 自动完成不会呈现结果
- .net - 带有验证的文本框。即使输入的文本无效,如何更新目标属性?
- javascript - 如何在每个项目上运行同步 POST?