0

I have this service

   service.getCurrentUser = function () {
        var def = $q.defer(); 
        if (service.user == null)
        {
            $http.get("./api/GetCurrentUser/")
            .success(function(data) { 
                service.user=data; 
                def.resolve(data); 
            }) 
            .error(function() { 
                def.reject("Failed to get user"); 
            }); 
        }
        else
            def.resolve(service.user);              
        return def.promise;
    } 

in my controller I want to call this and wait for return then if the user is in a certain group run other code

How do I write it so it uses the promise returned by the service

user1167777
  • 91
  • 2
  • 8
  • 1
    What's the name of the service? Where do you inject and call this method? Are you facing any problem? Please create a [mcve]. – 31piy Aug 24 '18 at 13:12
  • 2
    You mean you want to run some code after the Promise has been resolved? Use `.then`: `YourService.getCurrentUser().then(function(response){...}, function(error){...})` – Aleksey Solovey Aug 24 '18 at 13:13
  • `$http.get` already returns a promise; you should use that instead of creating a separate one. https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it – SLaks Aug 24 '18 at 13:39

1 Answers1

0

The promise implementation can be like:

service.getCurrentUser = function () {
    return new Promise((resolve,reject)=>{
        if (service.user == null) {
            $http.get("./api/GetCurrentUser/")
                .success(function (data) {
                    service.user = data;
                    resolve(data);
                })
                .error(function () {
                    reject("Failed to get user");
                });
        }else{
            resolve(service.user);
        }
    });
}

You can call it as:

    service.getCurrentUser()
    .then(user => {
        console.log('user', user);
    })
    .catch(error => { 
        console.log('error', error);
    });
Ketan Yekale
  • 2,108
  • 3
  • 26
  • 33