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.
});