在执行其他代码之前,确保for循环中的可观察对象均已完成 [英] Making sure observables in for loop are all finished before executing other code

查看:66
本文介绍了在执行其他代码之前,确保for循环中的可观察对象均已完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a piece of code that looks like this:

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

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

The problem is that doSomethingWithAddresses is executed before all the getAddress observables are finished. How can you make sure they are all finished before executing subsequent code?

推荐答案

您应该使用RxJS的

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


或者,您可以尝试使用此方法来防止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();
})

这篇关于在执行其他代码之前,确保for循环中的可观察对象均已完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆