My code starts with an empty array and I need to call a service that works with the populated array. Two service calls are used to populate the array, both fetching elements from an API. The issue is ensuring the last service call waits for the array to be fully populated before executing. This task becomes complicated due to having two separate service calls to wait for, each containing forEach loops. Any suggestions on how to solve this?
const subscribers: ISubscriber[] = [];
this.selectedChildren.forEach(child => {
this.serviceA.getSubscribers(child.id).subscribe( (subs: ISubscriber[]) => {
subs.forEach(s => {
subscribers.push(s);
});
});
});
this.selectedSubscribers.forEach(sub => {
this.serviceB.getSubscriber(sub.subscriberId).subscribe( (sub: ISubscriber) => {
subscribers.push(sub);
});
});
// subscribers is always empty when this call is made
// since above code hasn't finished executing
this.serviceC.processSubscribers(subscribers).subscribe( sub => {
this.toastr.success('Success!');
});
An attempt using async/await:
async doSomething(){
const subscribers: ISubscriber[] = [];
await this.selectedChildren.forEach(async child => {
await this.serviceA.getSubscribers(child.id).subscribe( (subs: ISubscriber[]) => {
subs.forEach(s => {
subscribers.push(s);
});
});
});
await this.selectedSubscribers.forEach(async sub => {
await this.serviceB.getSubscriber(sub.subscriberId).subscribe( (sub: ISubscriber) => {
subscribers.push(sub);
});
});
// subscribers is always empty when this call is made
// since above code hasn't finished executing
this.serviceC.processSubscribers(this.id, subscribers).subscribe( id => {
this.toastr.success('Success!');
});
}
Attempting to use Promise.all:
doSomething(){
const subscribers: ISubscriber[] = [];
const promises = [];
this.selectedChildren.forEach(child => {
promises.push(this.serviceA.getSubscribers(child.id).subscribe( (subs: ISubscriber[]) => {
subs.forEach(s => {
subscribers.push(s);
});
}));
});
this.selectedSubscribers.forEach(sub => {
promises.push(this.serviceB.getSubscriber(sub.subscriberId).subscribe( (sub: ISubscriber) => {
subscribers.push(sub);
}));
});
// subscribers is always empty when this call is made
// since above code hasn't finished executing
Promise.all(promises).then( a => {
this.serviceC.processSubscribers(this.id, subscribers).subscribe( id => {
this.toastr.success('Success!');
});
});
}