简体   繁体   English

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

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

I want to run some requests in parallel using forkJoin and combine their results as shown below.我想使用forkJoin并行运行一些请求并组合它们的结果,如下所示。 However, when one of the requests fails, the rest of the subscriptions are automatically cancelled by the browser.但是,当其中一个请求失败时,rest 的订阅将被浏览器自动取消。 What is a simple alternative to forkJoin that lets me run requests in parallel and if one subscription fails, the rest are allowed to complete?什么是forkJoin的简单替代方法,可以让我并行运行请求,如果一个订阅失败,则允许 rest 完成?

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

You can achieve that using forkJoin , however, you have to handle the errors for each sub Observable separately using catchError to prevent canceling the stream if any error occurred.您可以使用forkJoin实现这一点,但是,您必须使用catchError分别处理每个子Observable的错误,以防止在发生任何错误时取消 stream。

You can try something like the following:您可以尝试以下操作:

// 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]);
});

I would make a function like我会制作一个 function 之类的

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

and then use that instead of forkJoin .然后使用它代替forkJoin Then it's more reusable and can be unit tested.然后它更可重用并且可以进行单元测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM