javascript - AngularJs : Callback or promise in a service using conditions

标签 javascript angularjs callback angular-promise

我有一个特定的情况,我不确定是否应该实现回调或 promise 。我对 promise 完全陌生,刚刚开始理解它的概念。因此我不想陷入 anti patterns .

我也阅读并重新阅读了 Angular 文档 $q .

这就是我想要实现的:

如果使用 promise :

OauthService.token().then(function(access_token){
    config.url = config.url+'?access_token='+access_token;
});

return config;

如果使用回调:

OauthService.token(function(access_token){
    config.url = config.url+'?access_token='+access_token;
});

return config;

Oauth 服务不仅仅是一个 http 请求,如果它实际上有一些条件,可以让我认为我应该使用回调而不是 promise 。

所以我的服务现在使用回调。

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

    }
};

})

那么,如果我宁愿接受 promise ,我应该如何实现呢?

最佳答案

操作中的条件与回调与 promise 无关。普通回调是一种执行异步操作的蹩脚方式,您应该尽可能使用 Promise。

您可以重写您的 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);    
        }
    };
});

然后您可以进行一些重构,将其简化为:

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

关于javascript - AngularJs : Callback or promise in a service using conditions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30639796/

相关文章:

php - Google Maps API javascript 中的 WordPress query_posts(多个标记)

javascript - Lodash _.pluck 怎么了?

javascript - 如何将我的 current_user.id 传递给 AngularJs Controller

angularjs - 防止 AngularJS 使用缓存数据返回 Promise

javascript - 返回 $http 中的父函数

javascript - 使用 postgresql 和 pg-promise 在多行插入中找不到关系错误

javascript - 使用全局变量和多个js文件更好还是使用局部变量和一个长js文件更好?

javascript - 使用 Ajax 在 ExtJS 中进行异步数据检索和渲染

ios - 这是在 Swift 中使用回调的正确方法吗?

javascript - 在 Javascript 函数中连接数据