亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在繼續執行另一個函數之前等待所有 HTTP 請求返回

在繼續執行另一個函數之前等待所有 HTTP 請求返回

Cats萌萌 2021-11-12 16:16:53
我想等待三個 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...?
查看完整描述

3 回答

?
慕的地10843

TA貢獻1785條經驗 獲得超8個贊

forkJoin 是你的朋友。

(我在手機上,抱歉我的簡短)


查看完整回答
反對 回復 2021-11-12
?
三國紛爭

TA貢獻1804條經驗 獲得超7個贊

一旦所有 3 個請求都發出,組合最新將發出


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

});


查看完整回答
反對 回復 2021-11-12
?
忽然笑

TA貢獻1806條經驗 獲得超5個贊

最簡單的方法是“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

});


查看完整回答
反對 回復 2021-11-12
  • 3 回答
  • 0 關注
  • 259 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號