Valentin Grégoire
Valentin Grégoire

Reputation: 1150

AngularJS Synchronous call

In easily understandable pseudo code, I have this in AngluarJS. It is supposed to do a or b or both when we have c. The problem I have now is that the calls are asynchronously called and my data is screwed up.

if(a || c) {
    $http.get("path1");
}
if(b || c) {
    $http.get("path2");
}

As you see, I can't put the second GET into the .succes method of the first call because of the if statement. I could fiddle around with a function where the second get is listen in, but I think there should be a proper way to do this.

Upvotes: 1

Views: 219

Answers (3)

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

You could just hold of the promise object, that might be returned from the first a || c check ajax. If that satisfied/unsatisfied $q.when will resolve the promise by checking the promise value.

The reason behind using $q.when is if the promise will undefined then also .then function of $q.when going to resolve promise. Example Fiddle

And if promise will have promise object then it will wait till that promise gets resolved.

Code

var promise;
if(a || c) {
    promise = $http.get("path1");
}
$q.when(promise).then(function(response){
    if(b || c) {
       promise = $http.get("path2");
     }
}, function(error){
    //error
});

Upvotes: 2

Egan Wolf
Egan Wolf

Reputation: 3573

Why does if statement make a problem?

if(c)
    $http.get("path1").success(function(data){
        $http.get("path2")
    })
else
{
    if(a)
        $http.get("path1");
    else
        $http.get("path2");
}

Upvotes: 0

Joe Lloyd
Joe Lloyd

Reputation: 22323

Make your calls in a Factory

I don't fully see why you have a problem but maybe a separation of concerns will help you to see the full picture.

.factory('yourFactory', function($http){
    getFirstThing: function(){
        return $http.get("path1");
    },
    getSecondThing: function(){
        return $http.get("path2");
    }
});

Add the if statement to your controller

if(a || c) {
   yourFactory.getTheFirstThing;
}
if(b || c) {
   yourFactory.getTheSecondThing;
}

Upvotes: 0

Related Questions