i did lot of coding in angularjs. after time started feel comfortable , got productive. unfortunately there 1 thing don't understand:
within project need data through $http.get , restful api server. started stumble first. after implementing promise ($q.defer etc , .then) @ functions processing data that's necessary continue, thought conquered problem.
but in code:
$scope.getobservationsbylocations = function() { var promise = $q.defer(); var locationcount = 0; angular.foreach($scope.analysisdata, function(loc) { // each location $http.get($scope.api + 'device?_format=json', { // devices params: { location: loc.location.id } }).then(function (resultdevices) { var data = angular.fromjson(resultdevices); promise.resolve(data); // each device in location angular.foreach(angular.fromjson(resultdevices).data.entry.map(function (dev) { http.get($scope.api + 'observation?_format=json', { // observations params: { device: dev.resource.id } }).then(function (resultobservations) { var observations = angular.fromjson(resultobservations); // each obervation of device in location angular.foreach(observations.data.entry.map(function(obs) { $scope.analysisdata[locationcount].observations.push({observation: obs.resource}); })); }) })) }); locationcount++ }); return promise.promise }; i can't understand in order commands executed. since use webstorm ide , it's debugging feature, more accurate don't know why commands executed in order don't understand.
thinking simple, included in foreach have executed before return reached, because $http.get's connected through .then's. following debugging information, function iterates on locationcount++ , returns promise before goes deeper (meaning after first .then() ).
what's about? did misunderstood part of angularjs concept?
or bad practice , should reach out different solution?
if context important/interesting: objects based on i.e. https://www.hl7.org/fhir/2015may/location.html#5.15.3
with javascript can create single thread applications, although e.g. here not guaranteed that.
but talking real world , real browsers, code sample running single thread (by way same thread used rendering css , html, @ least in firefox).
when comes asynchronous call
$http.get($scope.api + 'device?_format=json', { it says "hey, can later". , waits because must go on current thread.
then, once current task done return can start getting remote data.
proof? check fiddle:
console.log(1); (var i=0;i<1000000;i++) settimeout(function(){ console.log(2); },0); console.log(3); you see spike for loop? moment when registers settimeout asynchronous calls. still 3 printed before 2 because task not done until 3 printed.
Comments
Post a Comment