-2

I need to get valid access token so I created a function for that

getValidAccessToken(){
    /*
    SOME CODE ...
    */

    if(!expired){
        return accessToken
    }
    else{
        // AJAX call for new token
        // return accessToken containing new token 
    }

}

So when I call getValidAccessToken() I want to get accessToken (current one or new one that will come from AJAX call)

Stevik
  • 1,092
  • 2
  • 16
  • 37

1 Answers1

0

You need to use promises. In Angular, this is best done with the $q service provider. You need to create a promise, and then return it from the method. Then in the method, resolve or reject the promise.

getValidAccessToken(){
    var deferred = $q.defer();
    /*
    SOME CODE ...
    */

    if(!expired){
        deferred.resolve(accessToken);
    }
    else{
        // AJAX call for new token
        $http.get('/some/url/accessToken')
            .success(function(data) {
                // return accessToken containing new token 
                deferred.resolve(data.accessToken);
            }).
            .error(function(error) {
                deferred.reject(error);
            });
    }

    return deferred;
}

Then, in the code that uses this method, call a method when the promise is resolved or rejected:

var tokenCall = getValidAccessToken();
tokenCall.then(function(token) {
    // Use the token somehow
}, function(error) {
    // Crap. There was an error.
});
searsaw
  • 3,492
  • 24
  • 31