I have a users service. I would like to create a method which utilizes another service I have built. There are two methods on this service. getUser()
and getCurrentUser()
. getCurrentUser()
utilizes the injected service which acquires the UID. It uses the returned UID to run the getUser()
method. My problem is that I can't get getCurrentUser()
to return the second tier promise.
This question is a little bit difficult to explain. Here's the code...
svs.service("usersService", function($rootScope, $http, loginService, alertBoxService) {
var self = this;
self.getUser = function(identifier, column) {
if (typeof(column) === 'undefined') column = "uid";
return $http.get($rootScope.api + "/getUser/" + identifier + "/" + column);
}
self.getCurrentUser = function() {
var currentUserPromise;
loginService.getCurrentUid().then(
function(response) {
if (response.data === "false") {
alertBoxService.trigger($rootScope.unexpectedApiResponse);
} else {
console.log(self.getUser(response.data));
currentUserPromise = self.getUser(response.data);
}
}, function(response) {
alertBoxService.trigger($rootScope.asyncFailed);
}
);
return currentUserPromise;
}
});
Chain the promises but don't forget to chain the rejections too...
self.getCurrentUser = function() {
return loginService.getCurrentUid().then(function(response) {
if (response.data === 'false') {
alertBoxService.trigger($rootScope.unexpectedApiResponse);
return $q.reject(response); // convert into a rejection
}
return self.getUser(response.data); // chain the promise resolution
}, function(response) {
alertBoxService.trigger($rootScope.asyncFailed);
return $q.reject(response); // chain the rejections
});
}
You'll need to inject the $q
service of course.
As Bergi kindly pointed out, you can also reject the promise by throwing an error instead of using $q.reject
, eg
throw response;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With