useyourbrian useyourbrian - 1 month ago 4x
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?



$scope.listings = {};

$scope.updateListings = function(){
$scope.listings =;

$scope.createListing = function(listingData){


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



@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:

    }, function(err){
       // handle error here