什么是 forkJoin 替代方案,它允许并行请求在其中一个失败时完成

What is a forkJoin alternative that allows parallel requests to complete if one of them fails

我想 运行 使用 forkJoin 并行处理一些请求并合并它们的结果,如下所示。 但是,当其中一个请求失败时,其余订阅将被浏览器自动取消。什么是 forkJoin 的简单替代方法,让我可以并行 运行 请求,如果一个订阅失败,其余的可以完成?

const posts = this.http.get("https://myApi.com/posts?userId=1");
const albums = this.http.get("https://myApi.com/albums?userId=1");

forkJoin([posts, albums]).subscribe((result) => {
  this.print(result[0], result[1]);
});

print(res1, res2) {
  const message = res1.text + res2.text;
  console.log(message);
}

您可以使用 forkJoin 实现此目的,但是,您必须使用 catchError 分别处理每个子 Observable 的错误,以防止在发生任何错误时取消流。

您可以尝试以下操作:

// import { catchError } from 'rxjs/operators';
// import { forkJoin, of } from 'rxjs';

const posts = this.http
  .get('https://myApi.com/posts?userId=1')
  .pipe(catchError((err) => of(err)));
const albums = this.http
  .get('https://myApi.com/albums?userId=1')
  .pipe(catchError((err) => of(err)));

forkJoin([posts, albums]).subscribe((result) => {
  this.print(result[0], result[1]);
});

我会做一个像

这样的函数
forkJoinReplaceErrors<T,R>(
  observables: Observable<T>[],
  ifError: ObservableInput<R>
) {
  return forkJoin(
    observables.pipe(
      catchError(() => ifError)
    )
  );
}

然后用它代替 forkJoin。然后它更可重用并且可以进行单元测试。