AngularJS $http.get 异步执行顺序

J.S*_*.S. 6 javascript json angularjs hl7-fhir angularjs-http

我最近在 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
};
Run Code Online (Sandbox Code Playgroud)

我无法理解命令的执行顺序。由于我使用 Webstorm IDE 和它的调试功能,所以说我不知道​​为什么命令以我不理解的顺序执行会更准确。

简单来说,forEach 中包含的所有内容都必须在返回之前执行,因为 $http.get 是通过 .then 连接的。但是根据调试信息,该函数迭代 locationCount++,甚至在它更深入之前(意味着在第一个 .then() 之后)返回承诺。

那是怎么回事?我是否误解了 AngularJS 概念的这一部分?

或者这只是非常糟糕的做法,我应该寻求不同的解决方案?

如果上下文很重要/有趣:对象基于即https://www.hl7.org/fhir/2015May/location.html#5.15.3

smn*_*brv 2

使用 JavaScript,您只能创建单线程应用程序,尽管例如这里他们说不能保证是这样。

但我们谈论的是现实世界和真实的浏览器,因此您的代码示例作为单个线程运行(顺便说一句,同一线程也用于渲染 CSS 和 HTML,至少在 Firefox 中)。

当涉及到异步调用时

$http.get($scope.api + 'Device?_format=json', { 
Run Code Online (Sandbox Code Playgroud)

它说“嘿,我可以稍后再做”。它会等待,因为它必须继续当前线程。

然后,一旦当前任务完成,return最终就可以开始获取远程数据。

证明?检查这个小提琴

console.log(1);

for (var i=0;i<1000000;i++) setTimeout(function(){
    console.log(2);
},0);

console.log(3);
Run Code Online (Sandbox Code Playgroud)

你看到带环的尖峰了for吗?这是它注册异步调用的时刻setTimeout。3 仍然先于 2 打印,因为直到打印 3 后任务才完成。