Search code examples
node.jsloopback4

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,


Solution

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