Making sure observables in for loop are all finished before executing other code

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();
})

Leave a Comment