javascript - 将 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 显示的。
解决方案
由于您正在异步执行操作,因此可能无法保证解决顺序。您可以使用索引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);
推荐阅读
- c# - 如何根据数据库结果动态添加面板
- python - 将字符串数组转换为数组 Python
- html - 文本未居中
- reactjs - 将 props 传递给高阶无状态功能 React 组件
- python - My list is being over sliced when writing to CSV
- webpack - 如何将 normalize.css 与 webpack 样式加载器一起使用?
- karate - karate - 无法从 0.7.0 版开始执行证书选择
- java - java中的所有软引用会一次性清除吗?
- c# - 当授权属性允许列出时,角色返回未授权
- c# - Get CheckedListBox item ValueMember