0

I have a service from which I am calling two functions in the controller. I want to check if the response of fucntionA is true and then only execute functionB

    var result= functionA();
    if(result === true){
     functionB();
    }

The if statement is already being executed without recieving the response from functionA and thus is always showing as false even when it should be true Note: functionA has an API call which is done using $http.get()

2 Answers2

0

The docs for $http have some good ideas.

The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise that is resolved (request success) or rejected (request failure) with a response object.

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
  // this callback will be called asynchronously
  // when the response is available
  if (response.result) {
    functionB()
  }
}, function errorCallback(response) {
  // called asynchronously if an error occurs
  // or server returns response with an error status.
});

Or us shortcut methods

Shortcut methods are also available. All shortcut methods require passing in the URL, and request data must be passed in for POST/PUT requests. An optional config can be passed as the last argument.

$http.get('/someUrl', config).then(successCallback, errorCallback);
ksav
  • 20,015
  • 6
  • 46
  • 66
0

As the functionA consumes $http.get() which returns a promise, you should chain the logic and implement your logic in the then method on the returned promise

Try it like this

functionA()
.then(function(result){
    if(result === true){
     functionB();
    }
});
Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69