-2

I know this has been asked before but I'm trying to figure out how to chain functions that contain ajax calls. What I have is:

$scope.firstFunc();
$scope.secondFunc();

secondFunc checks a scope value that is set from firstFunc. How can I chain this?

KingKongFrog
  • 13,946
  • 21
  • 75
  • 124

1 Answers1

0

If for example you have the following functions:

$scope.firstFunc = function() {
    return $http
        .get('/api/objects')
        .then(function(data) {
            $scope.data = data;
        });
};

$scope.secondFunc = function() {
    return $http
        .get('/api/otherObjects')
        .then(function(data) {
            // do something with new 'data' and with $scope.data
        });
};

you could call them in order like this:

$scope.firstFunc().then($scope.secondFunc);

Assuming I understood correctly.

$scope.firstFunc() returned the Promise $http.get returned (after it finished with its first .then chain)

And then, we chained another .then for that same Promise, and told it to execute $scope.secondFunc.

You could also just use the first ajax call's response data directly by using the following (if it fits your needs):

$scope.firstFunc = function() {
    return $http
        .get('/api/objects');
};

$scope.secondFunc = function(previousData) {
    return $http
        .get('/api/otherObjects')
        .then(function(data) {
            // do something with 'previousData' from the previous call from $scope.firstFunc
        });
};

and call everything with $scope.firstFunc().then($scope.secondFunc) so that $scope.secondFunc received $scope.firstFunc()'s data directly instead of passing through the $scope if that's somehow what you wanted in the first place, otherwise, the first part of this answer would do I think.

Hope this helped!

Amit
  • 4,274
  • 21
  • 25