javascript - 等待所有 HTTP 请求返回,然后再继续执行另一个函数

标签 javascript angular typescript

我想等待三个 HTTP 请求完成,然后再调用另一个函数来处理这三个 HTTP 请求返回的数据。

我尝试循环房间数量(相当于所需的 HTTP 请求数量),然后将设备推送到数组中。在将设备数组传递给下一个要处理的函数之前,我需要完成所有三个 HTTP 请求。

getDeviceListByRoom(rooms_id_array: string[]) {
    console.log('The rooms_id_array is: ', rooms_id_array);
    this.room_device_map = new Map;
    let count = 0;
    for (const id of rooms_id_array) {
      const devicesByRoom = this.Services.getDeviceByRoom(id);
      devicesByRoom.subscribe((res: any) => {
        if (res.code === 200) {
          // this statement will map the list of devices to the room.
          this.room_device_map.set(id, res.data);

          // this statement will just push the list of devices from different room into one array.
          this.all_devices_list.push(res.data);
          console.log('count is: ', count++);
        }
      }, err => {
        console.error('ERROR', err);
      });
      console.log('In all_devices_list is: ', this.all_devices_list);
    }
    console.log('Lalalalal');
  }

The code above will return 'Lalalala' first followed by the console print out of the count variable. Understandably, the for...of function is non blocking...?

最佳答案

forkJoin 是你的 friend 。

(我在移动设备上,抱歉我的简短)

关于javascript - 等待所有 HTTP 请求返回,然后再继续执行另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58279137/

相关文章:

JavaScript 错误/故障?

jquery - 如何使用显示的所有 Div 的 Jquery 从属性 'data-sort' 创建数组?

javascript - 在 node.js 中加载和执行外部 js 文件并访问局部变量?

javascript - 重新映射 json 对象并将它们推送到一个数组中

typescript - 命名泛型函数的返回类型

javascript - morris.js 中 x 轴的问题

javascript - 工厂注入(inject)指令不起作用

node.js - 使用 Nodemailer 时如何修复 "await is only valid in async function"错误

typescript - 将Typescript与Electron 9结合使用时出错

typescript |数组。错误 TS2339 : Property 'from' does not exist on type 'ArrayConstructor'