仅在异步功能执行后执行功能

时间:2020-06-06 04:10:26

标签: javascript angular typescript

我希望F1()等待F2()完全执行并获得rest调用响应并设置一些数据。

我尝试使用此代码

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

3 个答案:

答案 0 :(得分:0)

检查此 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

    }

答案 1 :(得分:0)

您可以这样做:

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

答案 2 :(得分:0)

您可以使用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);
    })
  );
}