简体   繁体   English

AngularJs:使用条件在服务中进行回调或承诺

[英]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. 我有一个特殊的情况,我不确定是否应该实现回调或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 . 我也阅读并重新阅读了有角度的文档$ 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. 如果Oauth服务实际上有一些条件,它不仅是一个http请求,可能会让我认为我应该使用回调而不是promises。

So here my service using callback for now. 所以这里我的服务现在使用回调。

OauthService.js : 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? 因此,如果我宁愿遵守承诺,我应该如何执行呢?

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. 普通的回调是执行异步操作的一种卑鄙的方式,您应尽可能使用Promise。

You can rewrite your token method to use promises like this: 您可以重写token方法以使用如下所示的promise:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM