【问题标题】:Rxjs wait for response and run method againRxjs 等待响应并再次运行方法
【发布时间】:2021-12-01 19:38:53
【问题描述】:

我有代码,检查状态,如果状态不是CompletedFailed,重试调用

这里是代码

    getRecognitionById() {
    this.loaderService.show(null, true);
    this.vendorWebApiService
      .createRecognition(this.executiveChangeId)
      .pipe(take(1))
      .subscribe((res) => {
        this.refresher$ = interval(5000);
        this.refreshSub = this.refresher$.subscribe(() => {
          this.checkStatus(res.taskRequestId);
          if (this.jobStatus === "Completed") {
            this.refreshSub.unsubscribe();
            this.getLatestFeedback();
            this.loaderService.hide(true);
          }
          if (this.jobStatus === "Failed") {
            this.loaderService.hide(true);
            this.refreshSub.unsubscribe();
            alert("Recognition failed. Try again later");
          } else {
            if (this.checkCount < 36) {
              this.checkStatus(res.taskRequestId); //run check status again only when we get response
            } else {
              this.loaderService.hide(true);
              this.refreshSub.unsubscribe();
              alert("Recognition failed. Try again later");
            }
          }
        });
      });
  }

我需要等待来自checkStatus() 方法的响应,然后才能再次运行checkStatus()(我注释了需要实现此逻辑的部分代码)

这是checkStatus方法的代码

 checkStatus(taskRequestId: number) {
    this.checkCount++;
    this.vendorWebApiService
      .getRecognition(taskRequestId, this.executiveChangeId)
      .pipe(take(1))
      .subscribe((recognitionResponse) => {
        this.jobStatus = recognitionResponse.jobStatus;
        if (recognitionResponse.jobStatus === "Completed") {
          this.recognitionData = recognitionResponse;
        }
      });
  }

我怎样才能做到这一点?

【问题讨论】:

  • 在这里使用像 switchMap() 这样的 rxjs 管道运算符很好。
  • 你能说明我需要如何以及在哪里使用它吗? @GaurangDhorda
  • 先用stackblitz做这个代码demo,这样对理解更有帮助

标签: javascript angular typescript rxjs


【解决方案1】:

您的代码中有很多额外的位,所以我怀疑这会按原样编译。即便如此,如果你解决了问题,这里有一个想法应该可行。

// By returning an observable that emits once the status is checked,
// we use emission to know when the status is checked.
checkStatus(taskRequestId: number): Observable<Status> {

  return this.vendorWebApiService.getRecognition(
    taskRequestId, 
    this.executiveChangeId
  ).pipe(

      take(1),

      /* This info is emitted directly into your stream now, so
      // you shouldn't need to se global variables here anymore.
      // uncomment this to get those gloabls being set again.
      // Up to you. 
      tap(recognitionResponse => {
        this.jobStatus = recognitionResponse.jobStatus;
        if (recognitionResponse.jobStatus === "Completed") {
          this.recognitionData = recognitionResponse;
        }
      })
      */
  );

}

getRecognitionById() {

  this.loaderService.show(null, true);

  this.vendorWebApiService.createRecognition(this.executiveChangeId).pipe(

    switchMap(res => this.checkStatus(res.taskRequestId).pipe(

      tap(({jobStatus}) => {
        if (jobStatus !== "Completed" && jobStatus !== "Failed") {
          throw "This is an error we can catch and retry with";
        }
      }),

      // If there's an error try again
      retryWhen(errors => errors.pipe(
        take(36), // Retry a max of 36 times
        s => concat(s, defer(() => {
          // After 36 retry attempts, we still failed
          this.loaderService.hide(true);
          alert("Recognition failed. Try again later");
          return EMPTY;
        })),
        delay(5000) // Wait 5 seconds before retry
      ))
    )),

    take(1)

  ).subscribe(recognitionResponse => {

    const {jobStatus} = recognitionResponse;

    if (jobStatus === "Completed") {
      this.recognitionData = recognitionResponse;
      this.getLatestFeedback();
    }

    if (jobStatus === "Failed") {
      alert("Recognition failed. Try again later");
    }

    this.loaderService.hide(true);

  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    相关资源
    最近更新 更多