0

In my code I am calling this function loadAllOrders();. This is the skeleton of its implementation,

$scope.loadAllOrders = function() {
    orderSvc.GetAllOrders().then(function(response) {
       // Does a bunch of stuff here
    });
}

GetAllOrders() uses a $http to get data from a database. loadAllOrders() then formats all the data and inserts them into an ng-repeat.

I want to be able to call a function when loadAllOrders() has finished. For example,

$scope.loadAllOrders().then(
    //I am doing something
);

How can this be achieved?

1
  • your promise to achieve this Commented Jul 12, 2016 at 15:32

1 Answer 1

3

You can write custom promise for loadAllOrders in angular JS

You have to inject $q service as a dependency on your controllers or service

$scope.loadAllOrders = function() {
var deferred = $q.defer();
    orderSvc.GetAllOrders().then(function(response) {
       // Does a bunch of stuff here
deferred.resolve(response);
    });
 return deferred.promise;
}

https://docs.angularjs.org/api/ng/service/$q

Hope this helps

Sign up to request clarification or add additional context in comments.

3 Comments

How do I then execute the function after the promise is returned?
$scope.loadAllOrders().then(function(result) { }); same as like you have written on your question
Beware of the promise anti-pattern. Just return orderSvc.GetAllOrders() to return the promise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.