Reputation: 801
i have this piece of code
var final=[];
$http.get('/Scenarios/List/'+ id).success(function(resp){
angular.forEach(resp, function(value, key){
var scenario ={};
scenario.data=[];
angular.forEach(value.samples, function(b, i){
$http.get('/sample/One/'+ b.id).then(function(result){
var id= result.temp_id;
var temp ={};
$http.get('/a/list/'+ id).then(function(result){
temp.a=result;
});
$http.get('/b/list/'+ id).then(function(result){
temp.b-resutl;
});
scenario.data.push(temp);
})
});
final.push(scenario);
});
});
console.log(final); //no value
basically when i tried to get a "final" data for further parsing, i discovered it is empty. I think the problem could be due to the missing usage of $q.all, but i have checked many tutorials online, i cant figure out a proper usage of $q.all to solve my repeat usage of angular.forEach, in my case, there are two. Any thoughts?
Upvotes: 0
Views: 68
Reputation: 7911
I'd like to solve it like this, using $q.all
is what you were missing as rightly mentioned in the question.
var final = [];
$http.get('/Scenarios/List/'+ id).success(function(resp){
processSamples(resp).then(function(final) {
console.log(final)
})
});
function processSamples(resp) {
var deferred = $q.defer();
angular.forEach(resp, function(value, key){
var scenario = {};
var promises = [];
scenario.data = [];
angular.forEach(value.samples, function(b, i){
promises.push($http.get('/sample/One/'+ b.id));
});
$q.all(promises).then(function(result) {
angular.forEach(result, function(res, index) {
var id= res.temp_id;
var temp = {};
var childpromises = [];
childpromises.push($http.get('/a/list/'+ id));
childpromises.push($http.get('/b/list/'+ id));
$q.all(childpromises).then(function(res) {
temp.a = res[0];
temp.b = res[1];
scenario.data.push(temp);
if(result.length === index + 1) {
final.push(scenario);
if(resp.length === key + 1) {
deferred.resolve(final);
}
}
})
})
})
});
return deferred.promise;
}
Notice how it resolves the returned promise once the uppermost loop is complete. Also, since there was no verifiable example provided, I might have left minor mistakes but it should probably give a good idea at least.
Upvotes: 1