myol
myol

Reputation: 9894

$http code firing at different times, how to fire in order

My knowledge of angular is extremely limited. EDIT: I am using $http.jsonp() to pull data from within an if statment

.controller('MagazineCtrl', function ($scope, $stuff ... )
    $scope.vars

    console.log('before if statement');

    if ($rootScope.attr === undefined )
    {
         $http.jsonp( url ).then{
               console.log('if statement');
         }
    }

    console.log('after if statement');

My output is

before if statement
after if statement
if statement

How can I get the code to run in the correct order? Is there a time-out function or something? I think a 'promise' may be what I'm looking for but I don't know if the code will still fire in order. How can I wait for the $http request to complete and complete the if statement before continuing?

Upvotes: 0

Views: 42

Answers (2)

makman99
makman99

Reputation: 1094

You could do something like this:

.controller('MagazineCtrl', function ($scope, $stuff ... ) {
    console.log('before if statement');

    function runAfter() {
        console.log('after if statement');
    }

    if ($rootScope.attr === undefined ) {
        $http.jsonp(url).then(function() {
            console.log('if statement');
            runAfter();
        });
    }
    else {
        runAfter();
    }
}

This way "after if" will always be run after the "if statement" but still run if $rootScope.attr is defined.

Upvotes: 1

bmleite
bmleite

Reputation: 26880

The call to $http.jsonp is async, which means the code will not block waiting for a response.

You should read your code like this:

.controller('MagazineCtrl', function ($scope, $stuff ... )
    console.log('before');

    if ($rootScope.attr === undefined ) {
       $http.jsonp( url ).then( function() {
         console.log('after');
       });
    }

If you need the result of the $http.jsonp call, then place the "after" code inside the then callback.

More information here.

Upvotes: 2

Related Questions