NestJs异步控制器方法与在方法内调用await/async

Cyr*_*ohn 10 node.js async-await nestjs

我对 NodeJs 和 NestJs 有点陌生。我一直想知道在控制器内使用异步作为方法返回类型与在常规方法内执行异步操作有什么区别?如果此 API 上存在巨大流量(例如 40K 请求/分钟),NodeJs 如何处理这两种情况下的请求。在第二个示例中它是阻塞的,在第一个示例中是非阻塞的还是会以类似的方式工作?

例如:

@Controller('cats')
export class CatsController {
  constructor(private catsService: CatsService) {}

  @Post()
  async sample() {
    return "1234";
  }
}
Run Code Online (Sandbox Code Playgroud)

@Controller('cats')
export class CatsController {
  constructor(private catsService: CatsService) {}

  @Post()
   function sample() {
    return await methodX();
  }
  
  async function methodX(){
      return "1234"
  }
Run Code Online (Sandbox Code Playgroud)

忽略sample()和methodX()中的内容仅作为示例。

Bab*_*boo 10

首先,将方法标记为使您可以在其中async使用关键字。await

例如,在您提供的第二个示例中,您需要将方法标记sample为:asyncawait methodX

@Post()
async function sample() {
  // Now `await` can be used inside `sample`
  return await methodX();
}
Run Code Online (Sandbox Code Playgroud)

所以回答你的问题

在控制器内使用异步作为方法返回类型与在常规方法内执行异步操作有什么区别?

空无一人。在这两种情况下,控制器的方法都需要标记为async。在方法主体中执行路由应该执行的操作或在另一个async方法中提取它只是代码组织的问题。

在第二个示例中它是阻塞的,在第一个示例中是非阻塞的还是会以类似的方式工作?

这两个示例都将以类似的方式工作。


其次,如果方法async主体中没有执行真正的异步操作(例如对另一个服务或setTimeout. 这意味着以下样本

// Sample 1
@Post()
async sample() {
  return "1234";
}

// Sample 2
@Post()
function async sample() {
  return await methodX();
}
  
async function methodX(){
  return "1234"
}
Run Code Online (Sandbox Code Playgroud)

都等价于同步方法

@Post()
syncSample() {
  return "1234";
}
Run Code Online (Sandbox Code Playgroud)

最后,正如 @Micael Levi 所说,return await在语法上是正确的,但应该避免。考虑这个样本:

@Post()
function async sample() {
  return await methodX();
}
  
async function methodX(){
  throw new Error('something failed')
}
Run Code Online (Sandbox Code Playgroud)

因为该方法sample return await methodX不会sample出现在堆栈跟踪中,这使得调试更加困难。

我们更喜欢这个示例:

@Post()
function async sample() {
  const result = await methodX();

  return result;
}
  
async function methodX(){
  throw new Error('something failed')
}
Run Code Online (Sandbox Code Playgroud)