【问题标题】:Waiting for all HTTP Request to return before proceeding with another function在继续执行另一个函数之前等待所有 HTTP 请求返回
【发布时间】:2019-10-08 10:20:29
【问题描述】:

我想等待三个 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...?

【问题讨论】:

标签: javascript angular typescript


【解决方案1】:

forkJoin 是你的朋友。

(我在手机上,对不起我的简短)

【讨论】:

    【解决方案2】:

    最简单的方法是“forkJoin”,在这种情况下,您也可以使用“zip”或“combineLatest”。

    试试这个:

    import { forkJoin } from 'rxjs';
    
    ...
    
    let req1 = this.http.get('xxx');
    let req2 = this.http.get('yyy');
    
    forkJoin([req1, req2]).subscribe(res => {
        // res[0] is from req1
        // res[1] is from req2
    });
    

    【讨论】:

      【解决方案3】:

      所有 3 个请求都发出后,Combine latest 将发出

      combineLatest(
        this.http.get('request1'),
        this.http.get('request2'),
        this.http.get('request3')
      ).subscribe(([response1, response2, response3]) => {
        // Here you can do stuff with response1, response2 and response3
      });
      

      【讨论】:

        猜你喜欢
        • 2017-11-05
        • 2011-08-16
        • 1970-01-01
        • 1970-01-01
        • 2012-03-06
        • 1970-01-01
        • 1970-01-01
        • 2020-03-01
        相关资源
        最近更新 更多