0

我觉得我在这里错过了一些非常简单的东西。我正在尝试为 fetch 创建一个简单的重试,但只有其中的代码retryWhen被执行。我正在使用 React,所以我没有this.http.get方便。也许这是一个问题from(/*promise*/)?我试图基于 这篇文章的重试逻辑。

这是我希望看到的:

Getting data from fetch...
In the retryWhen
In the interval
/* repeat the previous 3 lines 3x times including the Fetch */
Giving up

相反,我得到:

Getting data from fetch...
In the retryWhen
In the interval...
In the interval...
In the interval...
In the interval...
Giving up

所以它只是重复他 retryWhen 间隔中的代码,而不是重复原始的 fetchData 调用。我可能遗漏了一些对我的 RXJS 知识很重要的东西。

这是测试代码:

const fetchData = new Promise((res, rej) => {
  console.log("Getting data from fetch...");
  rej(); // just fail immediately to test the retry
});

const source = from(fetchData)
  .pipe(
    retryWhen(_ => {
      console.log("In the retryWhen");
      return interval(1000).pipe(
        tap(_ => console.log("In the interval...")),
        flatMap(count => count == 3 ? throwError("Giving up") : of(count))
      )
    }));

source.subscribe(
  result => console.log(result),
  err => console.log(err)
);

4

1 回答 1

2

更改为下面的代码,看看它是否有效。retryWhen向您传递一个错误流,如果有错误,它将继续发出。你返回一个timer来指定每次重试之间的延迟retryWhen。延迟后,它将为您重试可观察的源

const fetchData = defer(() => new Promise((res, rej) => {
      console.log('in promise')
        rej("Failed to fetch data"); 
      // fail the first 2 times
    }) );

const source = fetchData.pipe(
  retryWhen(err => {
    let count = 0;
    console.log("In the retryWhen");
    return err.pipe(
      tap(_ => {
        count++;
        console.log("In the interval...");
      }),
      mergeMap(_ => (count == 2 ? throwError("Giving up") : timer(2000)))
    );
  })
);

source.subscribe(result => console.log(result), err => console.warn(err));

https://codepen.io/fancheung/pen/gqjawe

于 2019-02-12T08:22:59.110 回答