首页 > 解决方案 > 将 promise 的结果推送到数组中

问题描述

我正在尝试清空,然后使用从承诺返回的值重新填充数组。但是,当我这样做时,它并不总是以相同的顺序添加它们。

$scope.$watch ('timeRange', function (newValue, oldValue, scope){
     $scope.chartdata = []
     //If a filter has changed, redraw all charts
     if (newValue !== oldValue)
     {
        for(var i = 0; i< $scope.charts.length; i++){
           $scope.draw($scope.charts[i]).then(function(value){
               $scope.chartdata.push(value);
           });
        }
     }
}, true);

这是用 ng-repeat 显示的。

标签: javascriptangularjsangular-promise

解决方案


由于您正在异步执行操作,因此可能无法保证解决顺序。您可以使用索引i而不是push

$scope.$watch ('timeRange', function (newValue, oldValue, scope){
     $scope.chartdata = []
     //If a filter has changed, redraw all charts
     if (newValue !== oldValue)
     {
        for(var i = 0; i< $scope.charts.length; i++){
           $scope.draw($scope.charts[i]).then(function(i) { // create scope to capture i
               return function(value) { $scope.chartdata[i] = value; };
           }(i));
        }
     }
}, true);

添加UPD示例只是为了演示 @georgeawg 作用域的工作原理

var arr = [1, 2, 3];

for (var i = 0; i < arr.length; i++) {
  setTimeout(function(i) {
    return function() {
      console.log(`Let's teach @georgeawg scopes ${i}`)
    }
  }(i), i * 1000)
}

或使用forEach

$scope.$watch ('timeRange', function (newValue, oldValue, scope){
     $scope.chartdata = []
     //If a filter has changed, redraw all charts
     if (newValue !== oldValue)
     {
        $scope.charts.forEach(function(chart, i) {
          $scope.draw(chart).then(function(value) {
             $scope.chartdata[i] = value;
          })
        })
     }
}, true);

Promise.all或使用或其 angularjs 模拟一次添加所有内容$q.all

$scope.$watch ('timeRange', function (newValue, oldValue, scope){
     $scope.chartdata = []
     //If a filter has changed, redraw all charts
     if (newValue !== oldValue)
     {
        $q.all($scope.charts.map(function(chart) {
          return $scope.draw(chart)
        }).then(function(chartdata) {
          $scope.chartdata = chartdata;
        })
     }
}, true);

推荐阅读