在nestjs中重试rxjs

lue*_*rro 0 rxjs nestjs

import { HttpService, Injectable } from '@nestjs/common';
import { retry } from 'rxjs/operators';

@Injectable()
export class XXXService {
  constructor(private http: HttpService) {}

  predictAll() {
    return this.http
      .post('https://xxxxx/xxxxx')
      .pipe(retry(5));
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我有以下代码来订阅上面的可观察值

import { Inject, Injectable } from '@nestjs/common';
import { XXXService } from '@api/services/XXX.service';

@Injectable()
export class YYYService {

  constructor(
    private readonly xxxService: XXXService
  ) {
    this.predictAll();
  }

  async predictAll() {
    await this.xxxService.predictAll().subscribe(
      ({ data }) => {
        console.log(data);
      },
      err => {
        console.log('error');
      }
    );
  }
}

Run Code Online (Sandbox Code Playgroud)

然后我尝试关闭我的互联网连接,经检查,“错误”仅在控制台中打印一次,这意味着我的可观察值根本没有重试。我这样做有什么问题吗?

Ben*_*esh 5

重试的预期行为让您感到困惑。

使用该retry运算符,在所有重试尝试都用尽之前,它不会将错误转发到错误处理程序。所以它正在重试,只是您的期望与如何记录错误有关。如果您想在重试之前记录发生的错误,则需要tap在以下操作之前使用产生副作用retry

source$.pipe(
   tap({ error: err => console.log('error: ', err.message) }),
   retry(5),
)
.subscribe({
  next: value => console.log(value),
  error: err => console.log('only fires once ', err.message),
});
Run Code Online (Sandbox Code Playgroud)

无关:你在那里用 async/await 做了一些奇怪的事情。

另外,这样做没有意义await source$.subscribe(),因为这样做时,你的函数只会返回Promise<Subscription>subscribe不返回Promise. 但是,请注意,您可能正在寻找Observable.prototype.forEach(),使用它将放弃取消,因为它不会返回用于Subscription取消订阅的 a 。

我建议在这种情况下不要使用async/ await

我希望这有帮助。