javascriptangularjsangular-promise

Conditional Chaining of $http-calls with Promises in AngularJS


I have to execute three different $http-calls sequentially which depend on each other. Until now my working solution is something like this:

$http.get(".../1/...").success(function() {
    $http.get(".../2/...").success(function() {
        $http.get(".../3/...").success(function() {
            
        });
    });
});

Now there is a certain change to be made: The first call should be skipped if a condition is true. I could do it like this:

if (skipCallOne) {
    $http.get(".../2/...").success(function() {
        $http.get(".../3/...").success(function() {
            
        });
    });
}
else {
    $http.get(".../1/...").success(function() {
        $http.get(".../2/...").success(function() {
            $http.get(".../3/...").success(function() {
                
            });
        });
    });
}

This obviously leads to massive code replication. I see that this could be reduced, if I used proper functions for the particular $http-calls. But as I understand, a better solution would be to use the $http-promises and properly chain them, like this:

$http.get(".../1/...").then(function() {
    return $http.get(".../2/...");
}).then(function() {
    return $http.get(".../3/...");
}).then(function() {
    
});

But now my question is, how can I conditionally skip the first call with the least code replication?


Solution

  • You can try this approach:

    $q.when(skipCallOne || $http.get(".../1/..."))
      .then(function() {
        return $http.get(".../2/...");
      }).then(function() {
        return $http.get(".../3/...");
      }).then(function() {
    });