【问题标题】:execute function only after async fucntion execute仅在异步函数执行后执行函数
【发布时间】:2020-06-06 13:28:30
【问题描述】:

我希望 F1() 等到 F2() 完全执行并获得休息呼叫响应并设置一些数据。

我用这个代码试过

this.F1().subscribe(result => {
  this.F2(result);
})


    F1() {


      return this.graphDataService.getAvailableSpan(a, b).subscribe(res => {
        this.c = new Date(res.lastAvailableDate);
        return 1;
      }, error => {
        this.lastAvailableDate = new Date();
        return 1;
      })
    }

【问题讨论】:

  • 你尝试过 promises 或 acync await
  • 我试过了,但是出错了,我确定我写错了代码
  • 您不能订阅订阅。

标签: javascript angular typescript


【解决方案1】:

检查这个 How can I call multiple API's on a function with Angular?

async apicall(){

      let data1 = await f1(); //your first function should return promises
      let data2 = await f2(); //your second function should return promises

    }

【讨论】:

    【解决方案2】:

    你可以这样做:

    async getAsyncCall() {
            this.result = await this.httpclient.get(this.URL).toPromise();
            this.F2(result);
        }
    

    【讨论】:

      【解决方案3】:

      您可以使用 RxJS 运算符来使流程异步。试试下面的

      ngOnInit() {
        this.F1().subscribe(result => {
          this.F2(result);
        });
      }
      
      F1(): Observable<any> {
        return this.graphDataService.getAvailableSpan(a, b).pipe(
          tap((res) => {
            this.c = new Date(res.lastAvailableDate);
          }),
          catchError((error) => {          // <-- `catchError` should return an obervable
            this.lastAvailableDate = new Date();
            return of(error);
          })
        );
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-19
        • 2013-02-02
        • 2021-09-27
        • 1970-01-01
        • 2015-12-06
        • 1970-01-01
        相关资源
        最近更新 更多