useyourbrian useyourbrian - 3 months ago 10
AngularJS Question

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) {
});
}

}

Answer

@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
    })