【问题标题】:JS wait for a funtion until it receives dataJS 等待一个函数,直到它接收到数据
【发布时间】:2020-11-02 14:10:03
【问题描述】:

当谈到首字母缩略词方法时,我总是陷入困境,因为我的代码遇到了一些问题。希望大家能帮帮我。

所以基本上,我在 onInit 上有 2 个功能;但是,当“fetchSalesbyDay2”运行时,this.firstResponse 正在接收未定义且不保存来自“fetchSalesbyDay1”的第一个响应

ngOnInit(): void {
    this.fetchSalesbyDay1();
    this.fetchSalesbyDay2();
}

fetchSalesbyDay1 = async () => {
    const params = {
        'reportName': 'home_report',
        'query': {
            'metric': 'salesByDay',
            'showBy': this.period.toString(),
            'startDate': parseInt(moment(this.range1sDate, 'MM-DD-YYYY HH:mm').format('X'), 10),
            'endDate': parseInt(moment(this.range1eDate, 'MM-DD-YYYY HH:mm').format('X'), 10)
        }
    };

    await this.http
        .post(this.GLOBALURL + '/reports/query', params, this.httpOptions1)
        .subscribe((response: any) => {
            this.firstResponse = response;
        });
}

fetchSalesbyDay2 = async () => {
    const params = {
        'reportName': 'home_report',
        'query': {
            'metric': 'salesByDay',
            'showBy': this.period.toString(),
            'startDate': parseInt(moment(this.range2sDate, 'MM-DD-YYYY HH:mm').format('X'), 10),
            'endDate': parseInt(moment(this.range2eDate, 'MM-DD-YYYY HH:mm').format('X'), 10)
        }
    };
    await this.http
        .post(this.GLOBALURL + '/reports/query', params, this.httpOptions1)
        .subscribe((response: any) => {
            this.secondResponse = response;
            this.displayandprocessWeekData(this.firstResponse, this.secondResponse);
        });
}

我希望这样,一旦“fetchSalesbyDay1”完成,并且 this.firstResponse 已经有一个值,“fetchSalesbyDay2”就可以执行。 解决这个问题的最佳方法是什么?

【问题讨论】:

标签: javascript angular asynchronous


【解决方案1】:

基本上没有理由将 observables 转换为 Promise。 Observables 为组合异步数据提供了更好的选择。在这种特定情况下,您可以使用 RxJS forkJoin 函数来组合两个可观察对象

试试下面的

import { forkJoin, Observable } from 'rxjs';

ngOnInit(): void {
  forkJoin({          // <-- use `forkJoin` to trigger HTTP requests in parallel
    firstRes: this.fetchSalesbyDay1(),
    secondRes: this.fetchSalesbyDay2()
  }).subscribe({
    next: ({firstRes, secondRes}) => {
      this.displayandprocessWeekData(firstRes, secondRes);
    },
    error: error => {
      console.log(error);
      // handle error
    }
  });
}

fetchSalesbyDay1(): Observable<any> { // <-- return the observable
  const params = {
    'reportName': 'home_report',
    'query': {
      'metric': 'salesByDay',
      'showBy': this.period.toString(),
      'startDate': parseInt(moment(this.range1sDate, 'MM-DD-YYYY HH:mm').format('X'), 10),
      'endDate': parseInt(moment(this.range1eDate, 'MM-DD-YYYY HH:mm').format('X'), 10)
    }
  };

  return this.http.post(this.GLOBALURL + '/reports/query', params, this.httpOptions1);
}

fetchSalesbyDay2(): Observable<any> { // <-- return the observable
  const params = {
    'reportName': 'home_report',
    'query': {
      'metric': 'salesByDay',
      'showBy': this.period.toString(),
      'startDate': parseInt(moment(this.range2sDate, 'MM-DD-YYYY HH:mm').format('X'), 10),
      'endDate': parseInt(moment(this.range2eDate, 'MM-DD-YYYY HH:mm').format('X'), 10)
    }
  };
  
  return this.http.post(this.GLOBALURL + '/reports/query', params, this.httpOptions1);
}

【讨论】:

    【解决方案2】:

    在不更改代码的情况下,您可以在 fetch 函数之外添加 await,如下所示:

    fetchSales = async () => {
       await fetchSalesbyDay1();
       await fetchSalesbyDay2();
    }
    

    这样 fetchSalesbyDay2() 将等待第一个完成。

    【讨论】:

      【解决方案3】:

      您不需要将async/await 与可观察对象一起使用。如果你想在响应到来后执行另一个函数,只需在属性分配后在你的订阅中执行它,就像这样:

      .subscribe((response: any) => {
          this.firstResponse = response;
          this.fetchSalesByDay2();
      });
      
      

      你可以删除所有async/await

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-16
        • 2019-05-11
        相关资源
        最近更新 更多