Kikapi
Kikapi

Reputation: 369

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?

Upvotes: 1

Views: 50

Answers (5)

John F.
John F.

Reputation: 4840

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.

Upvotes: 2

tottomotto
tottomotto

Reputation: 2352

Angular's $http methods run asynchronously. This means the console.log($scope.data); will be excecuted first and the console.log(result.data) inside then will be excecuted when the promise from $http resolves.

Upvotes: 1

Sari Rahal
Sari Rahal

Reputation: 1955

This is because Angular's JavaScript runs asynchronously. This means that It will keep running even though it's waiting on another task. You should look up angular's guild on Promises.

Upvotes: 0

Steve Ives
Steve Ives

Reputation: 8134

Because the http.get is asynchronous i.e. it goes off and does something on another thread, whilst the rest of the program continues. By the time it's finished, and done it's console.log, the '2nd' console.log has already run.

Upvotes: 4

divyam
divyam

Reputation: 132

$http is the service which will be performed asynchronously

Upvotes: 0

Related Questions