1

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.

Emilio Numazaki
  • 836
  • 1
  • 5
  • 25
  • The point of async/await is to not have to use `then` and callbacks. I don't know if that is the issue but something to point out. – Phix Oct 14 '20 at 02:14
  • Actually userService.getUserById returns a Promise... This is the reason I have used `then`. – Emilio Numazaki Oct 14 '20 at 09:36

1 Answers1

2

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;

}
programmer
  • 743
  • 4
  • 10
  • Hello @programmer, it also doesn't work. Please note `this.userService.getUserById `returns a Promise, this is the reason I've tried with `.then`. In this case, it returns 200 but with no content `{}`. If I add log after service call, it gets out when service returns. – Emilio Numazaki Oct 14 '20 at 09:35
  • I found what was wrong. Actually your answer works well. I was evaluating `result` wrong, I mean, when it returns, there is a enclosing attribute called `body` before actual attributes, for instance: `user.cpf = result?.body?.username`. I got it when debugging. Thank you! – Emilio Numazaki Oct 14 '20 at 10:20