Kikapi Kikapi - 1 month ago 9
AngularJS Question

Code runs in a different order than expected

JS

<script type="application/javascript">
var app = angular.module("app", []);

app.controller("AppCtrl", function ($scope, $http) {
$scope.data = [];
$http.get("{{ url_for('data') }}")
.then(function (result) {
$scope.data = result.data;
console.log(result.data); //first
});
console.log($scope.data); //second
...
</script>


first
console.log
returns the correct data (Array with one item), the second one returns empty Array.

Notice that the order of execution is not as the code:

Console

Array [ ]
Array [ "data" ]


Why the second console.log executes before the first one, How can it be fixed?

Answer

The call to $http.get is asynchronous so you don't know up-front how long it will take. console.log($scope.data) will be executed immediately following the $http.get request because the request will still be processing and waiting to return.

If you want to execute logic after your requests complete, you can add additional logic inside of the your then() and then chain them if you require additional requests to be executed. For instance,

              $http
              .get("{{ url_for('data') }}")
              .then(function (result) {
                  $scope.data = result.data;
                  // do more things
                  return $http.get('foo/bar')
              }).then(function (fooBar) {
                 // $scope.foo = bar;
              });

All $http calls return a promise so you're able to leverage the $q service to facilitate any promise specific functionality.