Kikapi Kikapi - 1 year ago 58
AngularJS Question

Code runs in a different order than expected


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

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

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:


Array [ ]
Array [ "data" ]

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

Answer Source

The call to $http.get is asynchronous so you don't know up-front how long it will take. console.log($ 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,

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download