Reputation: 1
I want to wait for three HTTP requests to complete before calling another function to work on the data returned by the three HTTP requests.
I tried looping the number of rooms (equivalent to the number of HTTP requests required) and then pushing the devices into an array. I need all three HTTP requests to be completed before passing the array of devices to the next function to work on.
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...?
Upvotes: 0
Views: 59
Reputation: 21638
Combine latest will emit once all 3 requests have emitted
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
});
Upvotes: 0
Reputation: 66
The easiest way is 'forkJoin', in such situations you can use 'zip' or 'combineLatest' too.
Try this:
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
});
Upvotes: 0