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 回答

三國紛爭
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
});

忽然笑
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
});
添加回答
舉報
0/150
提交
取消