如何使用正确的打字稿推断跳过 RxJS 中的延迟错误?



我只想记录一个错误并跳过此步骤,但有延迟和真正的打字稿推断。

const fetch = () =>
Math.random() > 0.5
? Promise.resolve("Success")
: Promise.reject("Some error");
const x = timer(0, 1000).pipe(
mergeMap(() => fetch()),
catchError((err, caught) => {
console.log("Error: ", err);
return caught; // After this a pipe starts again, but without delay, because a timer starts with 0 !!!
}),
);
x.subscribe((data) => {
console.log(data);
});

我需要在捕获错误后进行延迟。

您是否只希望在捕获错误后出现延迟?您提供的代码中可能存在无意的错误,因为从技术上讲,流在发生错误后结束。通过将返回值更改为正确的错误,您可以理解我的意思,如下所示:

const x = timer(0, 1000).pipe(
mergeMap(() => fetch()),
catchError((err) => { // "caught" is not needed, it isn't really anything.
console.log("Error: ", err);
return of(err); // If you return the error properly, the stream will end on error as expected behavior.
}),
);

我怀疑您真正想做的是使用延迟计时器重试,您可以通过这样做来实现:

const x = timer(0, 1000).pipe(
mergeMap(() => fetch()),
retryWhen(errors =>
errors.pipe(
tap(errors => console.log('Error: ', errors)),
delayWhen(() => timer(3000))
)
)
);

每当 x 秒后发生错误时,这将重试。

最新更新