You should make use of RxJS's forkJoin to wait for the for..of loop to be completed before returning all the observables.
Here are the changes you should make to your code:
getPersons().subscribe(
persons => {
const observablesList = [];
for (const person of persons) {
const getAddressObservable = getAddress(person.id);
observablesList.push(getAddressObservable)
}
forkJoin(observablesList).subscribe(response => {
// console.log(response) to check that there is a list of returned observables
const result = persons.map((person, index) => {
person['address'] = response[index]['address'];
return person;
})
doSomethingWithAddresses();
})
}
);
Alternatively, you may try this to prevent the chaining of subscribe()
getPersons().pipe(
mergeMap(persons => {
const observablesList = [];
for (const person of persons) {
const getAddressObservable = getAddress(person.id);
observablesList.push(getAddressObservable)
}
return observablesList;
})
).subscribe(response => {
// console.log(response) to check that there is a list of returned observables
const result = persons.map((person, index) => {
person['address'] = response[index]['address'];
return person;
})
doSomethingWithAddresses();
})
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…