在 Angular 中等待递归 forkJoin [英] Await recursive forkJoin in Angular

查看:56
本文介绍了在 Angular 中等待递归 forkJoin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图找出我是否可以在递归 forkJoin 中等待所有 http 调用.如何等待 forkJoin 中的所有 http 调用并收到最终结果?

Trying to find out can I await for all http calls in a recursive forkJoin. How can I await for the all the http calls in forkJoin and receive the final result?

目前我有类似以下内容

public myMethod(urls: string[]) {

...

return forkJoin(observables)
        .pipe(map(() => {
          if (json.urls !== 0) {
            return this.myMethod(json.urls);
          }
        }),   catchError((err) => {
          console.log(err);
          return of(null);
        })
        );
}

And then I subscribe ...

public mainMehtod(){
  return this.myMethod([json]).pipe(map(() => {
      ...some stuff here. But I need here the final result from the finished recursion
    }));

编辑

我找到的解决方案是,在递归中收集所有可观察对象,然后调用 forkjoin.

Well the solution I found was, collecting all the observables in a recursion and then calling the forkjoin.

推荐答案

expand 是一个很好的方法.使用提供的代码很难使它精确,但它看起来像这样:

expand is a good way to go here. tough to make it precise with the provided code but it'd look like this:

private _myMethod(urls: string[]) {

  ...

  return forkJoin(observables).pipe(
    catchError(err => {
      console.log(err)
      return of(null)
    })
  )
}

public myMethod(urls: string[]) {
  return this._myMethod(urls).pipe(
    // expand will feed the value of outter observable to start, and then call this function recursively with the result of subsequent calls inside expand
    expand(json => {
      if (json.urls.length) {
        // expand calls itself recursively
        return this._myMethod(json.urls);
      }
      return EMPTY; // break
    }),
    // expand emits outter result and then results of recursion one by one. how you collect this is up to you
    // reduce is an option to collect all values in an array like this (like a forkJoin of your forkJoins)
    // reduce((acc, val) => acc.concat([val]), []) 
    // last is an option if you only want the last recursive call (or first if none from recursion)
    // last()
    // or omit these entirely if you want the results one by one.
  )
}

这篇关于在 Angular 中等待递归 forkJoin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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