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

问题描述 投票:0回答:1

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

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

我需要在发现错误后进行延迟。

rxjs rxjs6
1个回答
0
投票

您是否只是想在发现错误后才进行延迟?您提供的代码可能存在意外错误,因为从技术上讲,流是在发生错误后结束的。您可以通过将返回值更改为适当的错误来理解我的意思,如下所示:

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秒后发生错误时,将重试。

© www.soinside.com 2019 - 2024. All rights reserved.