After spending a significant amount of time coding in AngularJS, I finally reached a point where I felt comfortable and productive. However, there is one aspect that continues to confuse me:
Specifically, within my project, I am required to retrieve data using $http.get and a RESTful API server. This is where I encountered my first roadblock. I implemented promises ($q.defer, etc.) in functions that process essential data to move forward, believing I had resolved the issue.
Yet, when looking at this code:
$scope.getObservationsByLocations = function() {
var promise = $q.defer();
var locationCount = 0;
angular.forEach($scope.analysisData, function(loc) { // for each location
$http.get($scope.api + 'Device?_format=json', { // get all devices
params: {
location: loc.location.id
}
}).then(function (resultDevices) {
var data = angular.fromJson(resultDevices);
promise.resolve(data);
// for each device in this location
angular.forEach(angular.fromJson(resultDevices).data.entry.map(function(dev) {
http.get($scope.api + 'Observation?_format=json', { // get all observations
params: {
device: dev.resource.id
}
}).then(function (resultObservations) {
var observations = angular.fromJson(resultObservations);
// for each observation of that device in this location
angular.forEach(observations.data.entry.map(function(obs) {
$scope.analysisData[locationCount].observations.push({observation: obs.resource});
}));
})
}))
});
locationCount++
});
return promise.promise
};
I find myself puzzled by the order in which commands are executed. Even with the debugging feature in Webstorm IDE, it seems unclear why the commands follow a sequence that I cannot comprehend.
In theory, everything within the forEach loop should execute before reaching the return statement due to the chained $http.get requests via .then(). However, during debugging, the function appears to iterate over locationCount++ and return the promise even before delving deeper (after the initial .then()).
Is there a gap in my understanding of this aspect of AngularJS, or is this simply poor practice that warrants exploring alternative solutions?
If necessary or of interest, the objects are derived from sources such as