I'm an newbie to angular promise. I just wanted to know, how to resolve the promise synchronously. For example,
var app = angular.module("app", []);
app.service("githubService", function($http, $q) {
var deferred = $q.defer();
this.getAccount = function() {
console.log(2)
return $http.get('https://api.github.com/users/haroldrv')
.then(function(response) {
// promise is fulfilled
deferred.resolve(response.data);
return deferred.promise;
}, function(response) {
// the following line rejects the promise
deferred.reject(response);
return deferred.promise;
});
};
});
app.controller("promiseController", function($scope, $q, githubService) {
console.log(1)
githubService.getAccount()
.then(
function(result) {
console.log(3)
// promise was fullfilled (regardless of outcome)
// checks for information will be peformed here
$scope.account = result;
},
function(error) {
console.log(3)
// handle errors here
console.log(error.statusText);
}
);
console.log(4)
});
In the above code, the values are printed in the following order 1,2,4,3. That is the service is called and getting the response synchronously. But before it resolve that http promise it received, it reaches the next line. I tried using another defer inside the response, but it doesn't work. So how to reach '4' after '3'? Here is the plunker link, http://plnkr.co/edit/AI8OJAgqFDVXb1fRYbix?p=preview
Any help on this would be greatly appreciated.