Brieuc
Brieuc

Reputation: 4114

AngularJs : Callback or promise in a service using conditions

I have a specific case where i'm not sure if i should implement a callback or promise. I'm totally new to promises and just starting to understand its concept. Therefor i'd like to not fall into an anti patterns.

I did also read and re-read the angular doc $q.

So that is what i would like to implement :

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;

Oauth service is not just an http request if actually has some conditions in it that could let me think that i should use callback instead of promises.

So here my service using callback for now.

OauthService.js :

app.factory('OauthService', function($http, $localStorage) {

return {
    token : function(callback){

        // Get actual token
        access_token = $localStorage.getObject('access_token');
        // Get actual identity
        identity_token = $localStorage.getObject('identity_token');

        // IF no user logged
        if(isObjectEmpty(identity_token)){

            // IF access_token does NOT exist OR will expires 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
        else{

            // IF access_token does NOT exist OR will expires 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 of type or expired)
        callback(access_token.key);

    }
};

})

So if i'd rather go with promises how should i implement that?

Upvotes: 0

Views: 188

Answers (1)

JLRishe
JLRishe

Reputation: 101672

Having conditions in your operation has nothing to do with callbacks vs. promises. Plain callbacks are a crappy way to do asynchronous operations and you should use promises whenever you can.

You can rewrite your token method to use promises like this:

app.factory('OauthService', function($http, $localStorage, $q) {
    return {
        token : function(callback){

            // Get actual token
            access_token = $localStorage.getObject('access_token');
            // Get actual identity
            identity_token = $localStorage.getObject('identity_token');

            // IF no user logged
            if(isObjectEmpty(identity_token)){

                // IF access_token does NOT exist OR will expires soon
                if( isObjectEmpty(access_token) || 
                    Date.now() > (access_token.expires_at - (600*1000)) ){

                    // Create an anonymous access_token
                    return $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 response.data.access_token;
                        });
                }
            }

            // IF user is logged
            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
                    return $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 response.data.access_token;    
                        });
                }

            }

            // return access token here (if the previous token has not changed of type or expired)
            return $q.when(access_token.key);    
        }
    };
});

And then you can do a bit of refactoring to reduce it to this:

app.factory('OauthService', function($http, $localStorage, $q) {
    function expiresSoon(access_token) {
        return Date.now() > (access_token.expires_at - (600*1000));
    }

    function getAccessToken(url, type) {
        return $http
            .get(url)
            .then(function (response) {
                $localStorage.setObject('access_token', {
                    key: response.data.access_token,
                    type: type,
                    expires_at: Date.now() + 
                        (response.data.expires_in * 1000)
            });

                return response.data.access_token;
            });
    }

    return {
        token : function(callback){

            // Get actual token
            access_token = $localStorage.getObject('access_token');
            // Get actual identity
            identity_token = $localStorage.getObject('identity_token');

            // IF no user logged
            if(isObjectEmpty(identity_token)){

                // IF access_token does NOT exist OR will expires soon
                if( isObjectEmpty(access_token) || expiresSoon(access_token) ) {
                    var url = domain + '/oauth/v2/token?client_id=' + public_id + 
                              '&client_secret=' + secret + '&grant_type=client_credentials';
                    // Create an anonymous access_token
                    return getAccessToken(url, 'anonymous');
                }
            }

            // IF user is logged
            else {
                // IF access_token does NOT exist OR will expire soon OR is anonymous
                if( isObjectEmpty(access_token) || 
                    expiresSoon(access_token) || 
                    access_token.type == 'anonymous' ){

                    var url = domain+'/oauth/v2/token?client_id=' + public_id+
                              '&client_secret='+secret + 
                              '&api_key='+identity_token + 
                              '&grant_type=http://oauth2.dev/grants/api_key';

                    // Create an access_token with an identity
                    return getAccessToken(url, 'identity');
                }
            }

            // return access token here (if the previous token has not changed of type or expired)
            return $q.when(access_token.key);    
        }
    };
});

Upvotes: 1

Related Questions