在执行其他代码之前,确保for循环中的可观察对象全部完成

时间:2019-04-15 09:21:59

标签: angular rxjs

我有一段看起来像这样的代码:

getPersons().subscribe(
    persons => {
        for (const person of persons) {
            getAddress(person.id).subscribe(
                address => {
                    person.address = address;
                }
            );
        }
        doSomethingWithAddresses();
     }
);

问题是在完成所有getAddress可观察对象之前执行了doSomethingWithAddresses。在执行后续代码之前,如何确保它们全部完成?

3 个答案:

答案 0 :(得分:2)

您应该使用RxJS的forkJoin等待for..of循环完成,然后再返回所有可观察值。

以下是您应该对代码进行的更改:

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

或者,您可以尝试这样做以防止链接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();
})

答案 1 :(得分:0)

let loadedPerson;
getPersons().pipe(
  mergeMap(persons => {
  return of(persons);
}),
mergeMap(person => {
  loadedPerson = person;
  return getAddresses(person.id);
}),
map((address) => {
  loadedPerson.address = address;
}),
tap(()=>{
  doSomethingWithAddresses();
})
).subscribe();

答案 2 :(得分:0)

尝试这种方法

methodOne() {
getPersons().subscribe(
    persons => {
        for (const person of persons) {
            getAddress(person.id).subscribe(
                address => {
                    person.address = address;
                }
            );
        }
     }
);
}

async methodTwo() {
await methodOne();
doSomethingWithAddresses();
}