Search code examples
angularjsangular-resourceangular-http

How can I synchronize two $resource calls in AngularJS


I am trying to do something like the following: In my controller I have functions that use $recource call to get data from database. The service 'myService'

var fillSubData = function (containerToFill) {
  resService.getSubDataFromDB(//$resource service
    {params},
    function (res) {
      //do something with containerToFill with the result res add new values
    }
  );
}

var fillData = function (containerToFill) {
  resService.getDataFromDB(//$resource service
    {params},
    function (res) {
      //do something with containerToFill with the result res
      fillSubData(containerToFill);
    }
  );
}

Controller

$scope.dataToFill;// object

var initialize = function () {
  //by reference
  myService.fillData(dataToFill);
  // I need the dataToFill filled to do other thing with data recovered and built
  angular.forEach(dataToFill.someArrayBuilt, function (item) {
    //do something with item...
  })
}

I need the dataToFill filled to do other thing with data recovered and built, but the resource calls are asyn, how can I do this?


Solution

  • Note that the resource actions return an object that contains a $promise property. You can use this to proceed with a callback once the async call has returned:

    myService.fillData(dataToFill).$promise.then(function() {
        // I need the dataToFill filled to do other thing with data recovered and built
        angular.forEach(dataToFill.someArrayBuilt, function (item) {
            //do something with item...
        })
    });
    

    To enable this, I suggest that you simply have your fillData method return the result of the resource call:

    var fillData = function (containerToFill) {
        return resService.getDataFromDB(//$resource service ...