最近我在使用AngularJS进行大量编码。经过一段时间的使用,我开始感到舒适并且变得非常高效。但不幸的是,有一件事情我不理解:
在我的项目中,我需要通过$http.get和RESTful API服务器获取数据。这是我第一次遇到问题。在对处理必要数据的函数实现promise ($q.defer等和.then)后,我以为已经解决了问题。
但在这段代码中:
$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 obervation 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
};
我无法理解命令的执行顺序。由于我使用Webstorm IDE及其调试功能,更准确地说,我不知道为什么命令以我不理解的顺序执行。
简单思考,forEach中包含的所有内容都必须在到达return之前执行,因为$http.get通过.then连接。但是根据调试信息,该函数遍历locationCount++,甚至在进入更深层次之前(即第一个.then()之后)就返回了promise。
这是怎么回事?我是否误解了AngularJS概念的这一部分?
还是这只是非常糟糕的做法,我应该寻求其他解决方案?
如果上下文很重要/有趣:对象基于例如https://www.hl7.org/fhir/2015May/location.html#5.15.3的内容。