Nodejs - Return from inside promise.then()

90 Views Asked by At

continuing to evolve in this new world of NodeJS, I'm trying to do something that seems to be usual but it doesn't work.

I have a service wrapper that calls HTTP/REST:

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

Here is the place I call it:

  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;
    })

  }

But it returns nothing. Off course there something wrong on response timming, I mean, function is returning before service call is complete.

I made similar question but it calls two services, waits for both and then returns. This case instead, calls just one service, create a payload and returns.

What's wrong? Thanks in advance.

1

There are 1 best solutions below

2
On BEST ANSWER

You can do it without then, as @Phix mentioned:

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;

}