【问题标题】:Waiting for the result of 2 asynchronous API calls before performing an operation在执行操作之前等待 2 次异步 API 调用的结果
【发布时间】:2018-03-03 18:22:47
【问题描述】:

我在页面加载时触发了 2 个异步 API 调用。我正在合计每个返回的值,然后计算它们的百分比变化。因此,我需要确保每个 API 都已成功调用,并且在计算差值之前已填充了保存总计的两个变量。

我现在所做的是使用$watchGroup 观察两个变量并在两个变量都不是null 时调用函数。这是我的控制器代码:

module Controllers {
    export class MyController {
        static $inject = ["$scope",'$http'];
        public TotalCurrent: any;
        public TotalPrevious: any;
        public diffPercent:any;
        constructor(
            private $scope: ng.IScope,
            private $http: ng.IHttpService,
        ) {
            this.$scope.$watchGroup(['myC.TotalCurrent', 'myC.TotalPrevious'], function (newVal, oldVal, scope) {
                if (newVal[0] != oldVal[0] && newVal[1] != oldVal[1] && newVal[0] != null && newVal[1] != null)
                    scope.myC.diffPercent = scope.myC.GetDifferencePercent(newVal[0], newVal[1]);
            });
                this.GetValuesFromAPI();
        }


        public GetValuesFromAPI() {
            this.TotalCurrent = null;
            this.TotalPrevious= null;


            this.$http.get("url1").then((result: any) => {
                if (result.value.length > 0) {
                    var TempCurrentTotal = 0;
                    for (var i = 0; i < result.value.length; i++) {
                        TempCurrentTotal += result.value[i].Val;
                    }
                    this.TotalCurrent = TempCurrentTotal;
                }

            });

            this.$http.get("url2").then((result: any) => {
                    if (result.value.length > 0) {
                        var TempPreviousTotal = 0;
                        for (var i = 0; i < result.value.length; i++) {
                            TempPreviousTotal += result.value[i].Val;
                        }
                        this.TotalPrevious= TempPreviousTotal;
                    }
                })
        }

        public GetDifferencePercent(current:any, last:any){
            var percentage = ((Math.abs(current - last) / last) * 100).toFixed(2);
            return percentage;
        }
    }
}

目前这工作正常。但是,我想知道是否有任何方法可以实现这一点,而不必担心与使用 $watchGroup 相关的性能问题,因为未来 API 调用的数量可能会增加,而且我的页面在 @987654325 上还有其他几个变量@。我考虑使用.then() 链接API 调用,但每个API 的响应时间都非常长,链接它们也会减慢页面速度。有什么建议吗?

【问题讨论】:

    标签: javascript angularjs typescript asynchronous


    【解决方案1】:

    您是否考虑过并行启动它们?

    你可以像这样使用$q

    const promise1 = this.$http.get("url1");
    const promise2 = this.$http.get("url2");
    
    this.$q.all([promise1, promise2]).then(results => {
      // results[0] is the result of the first promise, results[1] of the second.
    });
    

    您可以在类构造函数中注入 $q 服务。

    当两个 Promise 都完成时调用回调。如果需要,您还可以检查错误,只需附加一个 catch。

    【讨论】:

      猜你喜欢
      • 2016-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 2016-07-23
      相关资源
      最近更新 更多