将诺言的结果推入数组

时间:2018-06-26 15:04:36

标签: javascript angularjs angular-promise

我正在尝试清空,然后使用从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一起显示。

3 个答案:

答案 0 :(得分:1)

由于您正在执行异步处理,因此可能无法保证解析的顺序。您可以使用索引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);

答案 1 :(得分:-1)

错误代码段

function randInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function asyncFunc(index) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(index), randInt(0, 3000));
  });
}

const results = [];

for (var i = 0; i < 5; i++) {
  asyncFunc(i)
    .then((ret) => {
      results.push(ret);
    });
}

setTimeout(() => {
  console.log(results);
}, 4000);


带有片段的片段

我们可以在IEFF函数内部传递数据的位置。

function randInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function asyncFunc(index) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(index), randInt(0, 3000));
  });
}

const results = [];

for (var i = 0; i < 5; i++) {
  (function(j) {
    asyncFunc(i)
      .then((ret) => {
        results[j] = ret;
      });
  })(i);
}

setTimeout(() => {
  console.log(results);
}, 4000);

答案 2 :(得分:-1)

使用.mapPromise.all(或AngularJS中的$q.all())是实现此目的的一种干净方法。这样可以保持商品的顺序,并有一个额外的好处,即允许您检测何时已填充整个阵列。

从格雷戈里的答案中借用示例代码:

注意::以下内容使用setTimeoutnew PromisePromise.all来作为可运行的堆栈代码段提供简单的说明性演示在实际的AngularJS代码中,您不需要setTimeoutnew Promise,而应使用$q.all而不是Promise.all,如最后的示例所示)< / p>

function randInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function delay(ms) {
  return new Promise(function (resolve) { setTimeout(resolve, ms); });  
}

function asyncFunc(value) {
  return delay(randInt(0, 3000))
  .then(function () { 
      console.log(value, 'finished');
      return value * 2 + 1;
  });
}

const origArray = [0, 1, 2, 3, 4];

Promise.all(origArray.map(asyncFunc))
    .then(function (resultArray) {
      console.log(resultArray);
    });

将其应用于您的特定代码,我们将:

$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($scope.draw))
            .then(function (resultArray) {
                $scope.charts = resultArray;
            });
     }
}, true);