Emilio Numazaki
Emilio Numazaki

Reputation: 892

Function that calls two REST services and wait for both before return

I'm developing a microservice in Loopback4/NodeJS and I need to call two REST services in parallel but return only when both returns. In this case, I need to create a new object from results and then return.

This is the signature of REST service function:

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

And this is the way I'm trying to do (a sample code calling same service twice):

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

    console.log('1st call')
    const r1 = this.userService.getUserById(userId, undefined, undefined);

    console.log('2nd call...')
    const r2 = this.userService.getUserById(userId, undefined, undefined);

    await Promise.all([r1, r2]).then(function (results) {
      return results[0];
    });
  }

But it doesn't return anything (204).

I saw some examples around but it doesn't work in my case. What am I missing?

Thanks in advance,

Upvotes: 0

Views: 52

Answers (2)

DazDylz
DazDylz

Reputation: 1086

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

    console.log('1st call')
    const r1 = this.userService.getUserById(userId, undefined, undefined);

    console.log('2nd call...')
    const r2 = this.userService.getUserById(userId, undefined, undefined);

    return await Promise.all([r1, r2]).then(function (results) {
      return results[0];
    });
  }

Upvotes: 1

lanxion
lanxion

Reputation: 1430

It is doing something, it is infact returning even the status code 204, which stands for "no content" (list of all status codes here). So the status code pretty much implies that there is no content to be returned.

Upvotes: 0

Related Questions