This is the most basic situation that promises are for. You simply need to make a promise with var deferred = $q.defer() when beginning an async operation, resolve the promise with deferred.resolve(result) when the async operation is complete, and return deferred.promise in your function. Angular’s asynchronous methods do this internally and return promises already, so you can just return those same promises rather than creating new promises with $q.defer(). You can attach a .then to anything that returns a promise. Further, if you return a value from a then function, that value will be wrapped in a promise so that the then chain can continue
angular.module('myApp', [])
.factory('myService', function($q, $timeout, $http) {
return {
myMethod: function() {
// return the same promise that $http.get returns
return $http.get('some/url');
}
};
})
.controller('myCtrl', function($scope, myService) {
myService.myMethod().then(function(resp) {
$scope.result = resp.data;
});
})
And here is a bit more fun with the chaining:
.factory('myService', function($q, $timeout, $http) {
return {
myMethod: function() {
// return the same promise that $http.get returns
return $http.get('some/url').then(function() {
return 'abc';
});
}
};
})
.controller('myCtrl', function($scope, myService) {
myService.myMethod().then(function(result) {
console.log(result); // 'abc'
return someOtherAsyncFunc(); // for example, say this returns '123'
}).then(function(result) {
console.log(result); // '123'
});
})