调用两个REST服务并在返回之前等待两者的函数

问题描述

我正在Loopback4 / NodeJS中开发一个微服务,我需要并行调用两个REST服务,但是只有两个都返回时才返回。在这种情况下,我需要根据结果创建一个新对象,然后返回。

这是REST服务功能的签名:

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

这就是我要尝试的方式(两次调用相同服务的示例代码):

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

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

但是它什么也不返回(204)。

我看到了一些示例,但在我的情况下不起作用。我想念什么?

预先感谢

解决方法

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

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

它正在做某事,实际上返回的是状态码204,它代表“无内容” (所有状态码here的列表)。因此状态码几乎暗示着没有内容要返回。