user5314287
user5314287

Reputation:

How to call function only when async call from service is completed?

In my controller I have a createListing() function that is called when a form is submitted. createListing() then calls on the saveListing() function from within the newListingService service, which makes an $http post request to the database. I then need to update the listings shown on the page to include the newly created listing using the updateListings() function in the controller. The problem that I am having is that the updateListings() function is being called BEFORE the saveListing() call in createListing(). How can I make sure that updateListings() will only be called AFTER the post request is completed?

Controller:

 ...

  $scope.listings = {};

  $scope.updateListings = function(){
    $http.get('/listings')
       .then(function(res){
          $scope.listings = res.data;
        });
      };

   $scope.createListing = function(listingData){
     newListingService.saveListing(listingData);
     $scope.updateListings();
   };

newListingService:

function newListingService($http){
  this.saveListing = function(listingData){
    $http({
      method  : 'POST',
      url     : '/listings',
      data    : listingData
    })
    .success(function(data) {
    });
  }

}

Upvotes: 0

Views: 615

Answers (2)

Jahongir Rahmonov
Jahongir Rahmonov

Reputation: 13733

@depiction is right.You should use promises.

But, $http returns promise itself. Thus,you don't have to use $q or anything else. Just return the request and it will returns its promise:

this.saveListing = function(listingData){
   return $http({
            method  : 'POST',
            url     : '/listings',
            data    : listingData
          });
}

and in your controller:

newListingService.saveListing(listingData)
    .then(function(response){
        $scope.updateListings();
    }, function(err){
       // handle error here
    })

Upvotes: 1

depiction
depiction

Reputation: 819

You'll need to use promises.

function newListingService($http){
    this.saveListing = function(listingData){

    var deferred = $q.defer();

    $http({
      method  : 'POST',
      url     : '/listings',
      data    : listingData
    })
    .then(
        function success(data) {
            deferred.resolve(data);
        },
        function error(response) {
            deferred.resolve(false);
        }
    );

    return deferred.promise;

  }
}

Upvotes: 0

Related Questions