I am currently faced with a specific scenario where I am uncertain whether to implement a callback or a promise. As someone who is relatively new to promises and just beginning to grasp their concept, I want to avoid falling into any potential anti patterns.
I have thoroughly studied the Angular documentation on $q.
Here is what I aim to achieve:
If using promises :
OauthService.token().then(function(access_token){
config.url = config.url+'?access_token='+access_token;
});
return config;
If using callback :
OauthService.token(function(access_token){
config.url = config.url+'?access_token='+access_token;
});
return config;
The Oauth service contains some conditions that make me lean towards using callbacks instead of promises.
Therefore, my service currently utilizes callbacks.
OauthService.js :
app.factory('OauthService', function($http, $localStorage) {
return {
token : function(callback){
// Retrieve current token
access_token = $localStorage.getObject('access_token');
// Retrieve current identity
identity_token = $localStorage.getObject('identity_token');
// If no user is logged in
if(isObjectEmpty(identity_token)){
// If access_token does NOT exist OR will expire soon
if( isObjectEmpty(access_token) || Date.now() > (access_token.expires_at - (600*1000)) ){
// Create an anonymous access_token
$http
.get(domain+'/oauth/v2/token?client_id='+public_id+'&client_secret='+secret+'&grant_type=client_credentials')
.then(function (response) {
$localStorage.setObject('access_token', {
key: response.data.access_token,
type: 'anonymous',
expires_at: Date.now()+(response.data.expires_in*1000)
});
// return access token here
callback(response.data.access_token);
});
}
}
// If user is logged in
else{
// If access_token does NOT exist OR will expire soon OR is anonymous
if( isObjectEmpty(access_token) || Date.now() > (access_token.expires_at - (600*1000)) || access_token.type == 'anonymous' ){
// Create an access_token with an identity
$http
.get(domain+'/oauth/v2/token?client_id='+public_id+'&client_secret='+secret+'&api_key='+identity_token+'&grant_type=http://oauth2.dev/grants/api_key')
.then(function (response) {
$localStorage.setObject('access_token', {
key: response.data.access_token,
type: 'identity',
expires_at: Date.now()+(response.data.expires_in*1000)
});
// return access token here
callback(response.data.access_token);
});
}
}
// return access token here (if the previous token has not changed type or expired)
callback(access_token.key);
}
};
})
If I were to opt for promises, how should I go about implementing that?