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

How to skip error with delay in RxJS with a right typescript infer?

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

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

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

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

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