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

vcudknz3  于 10个月前  发布在  Java
关注(0)|答案(2)|浏览(73)

我想使用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);
}

字符串

mftmpeh8

mftmpeh81#

您可以使用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]);
});

字符串

yhived7q

yhived7q2#

我会创建一个函数

forkJoinReplaceErrors<T,R>(
  observables: Observable<T>[],
  ifError: ObservableInput<R>
) {
  const fReturnIfError = () => ifError;
  const array = observables.map(
    o$ => o$.pipe(
      catchError(fReturnIfError)
    )
  );
  return forkJoin(...array);
}

字符串
然后用它来代替forkJoin。这样它就更可重用,并且可以进行单元测试。

相关问题