在执行其他代码之前确保 for 循环中的 observable 都已完成 [英] Making sure observables in for loop are all finished before executing other code

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

问题描述

我有一段如下所示的代码:

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

问题是 doSomethingWithAddresses 在所有 getAddress observable 完成之前执行.在执行后续代码之前,如何确保它们都已完成?

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 的 forkJoin 等待 for..of 循环完成,然后返回所有可观察对象.

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 循环中的 observable 都已完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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