Node.js-从promise.then内部返回

问题描述

在NodeJS的这个新世界中继续发展,我正在尝试做一些看似平常的事情,但是那是行不通的。

我有一个调用HTTP / REST的服务包装器:

getUserById(id: string,attributes: string | undefined,excludedAttributes: string | undefined): Promise<any>;

这是我称之为的地方:

  async getUserById(@param.path.string('userId') userId: string): Promise<Usuario> {

    console.log('1st call')
    return await this.userService.getUserById(userId,undefined,undefined).then(result => {
      var user: Usuario = {};
      
      user.cpf = result?.username;
      user.id = result?.id;
      user.nome = result?.name?.formatted;
      
      return user;
    })

  }

但是它什么也不返回。当然,响应时间上有一些问题,我的意思是,函数在服务调用完成之前就返回了。

我做了类似的question,但是它调用了两个服务,等待两者,然后返回。相反,在这种情况下,仅调用一项服务,创建有效负载并返回。

怎么了?预先感谢。

解决方法

您可以不使用then来完成此操作,如@Phix所述:

async getUserById(@param.path.string('userId') userId: string): Promise<Usuario> {

  const result = await this.userService.getUserById(userId,undefined,undefined);
  var user: Usuario = {};
  
  user.cpf = result?.username;
  user.id = result?.id;
  user.nome = result?.name?.formatted;
  
  return user;

}