我觉得我在这里错过了一些非常简单的事情。我正在尝试为获取创建一个简单的重试方法,但是仅retryWhen
中的代码正在执行。我正在使用React,所以我没有this.http.get
的便利。也许与from(/*promise*/)
有关?我正在尝试根据this post建立重试逻辑。
这是我希望看到的:
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)
);
答案 0 :(得分:1)
更改为下面的代码,看看它是否有效。 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));