crowhill crowhill - 2 months ago 9
AngularJS Question

Handling a function where the return might (or might not) be async

I have the following function. It doesn't work, but the idea is that if a

sessionStorage
variable is already set, use it. If not, make a call to the API and then set the
sessionVariable
for next time.

isAdmin: function() {

// hit the first page, or refreshed.
if(sessionStorage.getItem("isAdministrator") === null) {
AzureGroupService.get({adGroup: "Programmers"}).$promise.then(function (data) {
sessionStorage["isAdministrator"] === data.isMember;
return data.isMember;
});
}
else {
return JSON.parse(sessionStorage["isAdministrator"]);
}
}


So the function might return immediately, or it might need to wait on the API. Is this even close to the right way to do this?

If so, how would I call it in a controller? Something like this?

user.isAdmin().then(function(response) {
vm.test = response.data;
});

Answer

You can use $q.when() , if the sessionStorage object is not null. Your isAdmin() function should look like this.

isAdmin: function() {

// hit the first page, or refreshed.
if(sessionStorage.getItem("isAdministrator") === null) {
    return AzureGroupService.get({adGroup: "Programmers"}).$promise.then(function (data) {
        sessionStorage["isAdministrator"] === data.isMember;
        return data.isMember;
    });
}
else {
    return $q.when(JSON.parse(sessionStorage["isAdministrator"]));
}
}

Your controller should look like this , isAdmin() function will always return a promise . So u can define a success callback using .then().

user.isAdmin().then(function(response) {
    vm.test = response.data;
});