如何处理数据时在一个循环的承诺? [英] How to deal the data when the promise in a loop?
问题描述
这是我的方式:
var activeArr = [];
var activeDate = [];
var day = (endDate - startDate) / (24 * 60 * 60 * 1000);
for (var i = 1; i < day + 1; i++) {
activeDate.push(endDate - (24 * 60 * 60 * 1000) * i);
var start = endDate - (24 * 60 * 60 * 1000) * i;
var end = endDate - (24 * 60 * 60 * 1000) * (i - 1);
statisService.getRegStatis(start, end).then(function(data) {
activeArr.push(data);
if(activeArr.length == day){
var active = [];
for(var j=0;j<activeArr.length;j++){
var obj = {};
obj.date = activeDate[j];
obj.data = activeArr[j].data;
active.push(obj);
}
$scope.active = active;
}
});
}
该服务:
userServiceModule.factory('statisService', ['$http', 'serverUrl', function($http, serverUrl) {
return {
getRegStatis: function(startDate, endDate) {
var url = serverUrl + "/adminDA/dbReport?startTime=" + startDate + "&endTime=" + endDate;
return $http.get(url).then(function(result) {
return result.data;
});
}
};
我想把日期和数据合并到一个对象,这样我可以在这样的视图中使用它:
I want to put the date and the data into one object so that I can use it in the view like this:
<tr ng-repeat="item in active track by $index">
for循环不会等待所有的服务调用完成,所以我处理的数据在for循环,我认为这不是一个好办法,但我不知道该怎么做的更好。
The for loop will not wait for all the service calls to be completed,So I deal the data in the for loop,and I think this is not a good way,but I don't know how to do it better.
推荐答案
您应该使用 $ q.defer()诺经理,从延期API 。
You should use the $q.defer() promise manager, from the deferred API.
$ q.defer()获得2种方法:
-
解析(值):这解决我们的相关承诺,给她终值
resolve(value) : which resolve our associated promise, by giving her the final value
拒绝(原因):其中一个解决错误的承诺
reject(reason) : which resolve an promise error.
另外的 $ q.all()采取承诺数组作为参数,并解决所有的人。
Moreover $q.all() take an promises array as parameter, and resolve all of them.
控制器
(function(){
function Controller($scope, Service, $q) {
var promises = [];
var defer = $q.defer();
//Process loop
for (var i = 0; i < 20; ++i){
//Fill my promises array with the promise that Service.post(i) return
promises.push(Service.post(i));
}
//Resolve all promise into the promises array
$q.all(promises).then(function(response){
//Create arr by maping each data field of the response
var arr = response.map(function(elm){
return elm.data;
});
//Resolve my data when she is processed
defer.resolve(arr);
});
//When the data is set, i can get it
defer.promise.then(function(data){
//Here data is an array
console.log(data)
});
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
服务
(function(){
function Service($http){
function post(num){
//Just an example, I've pass an object, and just return it then
return $http.post('path_to_url', {id:num});
}
var factory = {
post: post
};
return factory;
}
angular
.module('app')
.factory('Service', Service);
})();
这篇关于如何处理数据时在一个循环的承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!