javascriptangularjshttp-postngresource

angularjs - Sequentially call function that performs ngResource http post request


This is the outline of a function to perform and http post request to get all the entries from a table. This function is defined within my controller.

$scope.getAllData = function (tableName) {
  var allDataResults = $resource('/getAllDataForTable', {}, {
    save: {
      method: 'POST',
      timeout: 6000
    }
  });
  allDataResults.save($scope.all_data_input, function (response) {
    //Do stuff with response
    }
  });
};

I need to call this function sequentially for different tablenames. I tried simply calling it twice like this.

$scope.getAllData(tableName1);
$scope.getAllData(tableName2);

The second response comes in correct, but the first one is incorrect. Each response contains a list and the size of the second response's list is forced on the first one, causing the response to be incorrect. How do I properly chain these 2 post requests requests?


Solution

  • You need to return the promise from your function, i. e.:

    $scope.getAllData = function (tableName) {
      var allDataResults = $resource('/getAllDataForTable', {}, {
        save: {
          method: 'POST',
          timeout: 6000
        }
      });
      return allDataResults.save($scope.all_data_input, function (response) {
        //Do stuff with response
        }
      });
    };
    

    Then, you can chain your calls using the returned promise:

    $scope.getAllData(tableName1).$promise.then(function() {
      $scope.getAllData(tableName2);
    });
    

    Btw the $resource examples might help you understand it better. If you need to manage a lot of chained promises, you should look at $q.all.