转换为承诺解决http的异步性质

时间:2015-01-31 19:18:41

标签: angularjs promise angular-ui-router restangular

在我的登录屏幕上,当我点击"登录"按钮。它实际上是ng-submit =" login()"。代码在我的LoginCtrl控制器中。

 function onSuccessfulLogin() {
    $scope.failureMessage  = "";
    $rootScope.mainbody.position = 'absolute';

    if (nextState !== null && typeof nextState.name === 'string' && nextState.name !== '') {
        console.log("calling nextState ......");
        $state.go(nextState.name, nextState.params);
    } else {
        $state.go('main', {});
    }
}

$scope.login = function() {
    disableLoginButton();

    $rootScope.login = {
        goodmsg : true,
        errormsg : false
    }

    $scope.failureMessage  = "Signing in Analytics Dashboard ....";
    User.authenticate($scope.username, $scope.password, onSuccessfulLogin, onFailedLogin, $scope.persist);
};

我有一个名为User的服务,我打电话给"验证"单击上面的登录按钮后即可运行。它目前正常工作,直到我在#34; this.authenticate"内添加了更多的HTTP调用。功能。我想要发生的是将其转换为promise,以便在收到来自所有HTTP请求的所有数据时,它将在正确的时间调用onSuccessfulLogin()。但是,我不确定我将如何转换" this.authenticate"回报承诺。顺便说一下,TokenService是我制作的Restangular工厂。

此外,我想将其转换为承诺的原因是因为我想在ui-router实例化我将要显示的控制器之前确保所有数据都已准备好。

this.authenticate = function(username, password, successCallback, errorCallback, persistData) {

    this.removeAuthentication();

    TokenService.setResponseInterceptor(function (data, operation, what, url, response) {
        if (operation == 'post') {
            $rootScope.locationResourceId = response.headers('Location').split('/')[response.headers('Location').split('/').length-1]
        }
        return response.data;
    });

    TokenService.one('authentokens').customPOST({'email' :  username , 'password' : password}, '', {app : 'baam'})
        .then(function(data) {
            var userresourceId = data.href.split('/')[data.href.split('/').length-1]

            $rootScope.userData = {
                isAuthenticated : true,
                username : username,
                bearerToken : data.token,
                expirationDate : new Date(data['expires']),
                resourceId : userresourceId,
                tokenResourceId : $rootScope.locationResourceId
            };

            TokenService.one('users').customGET($rootScope.userData.resourceId, { 'token' : $rootScope.userData.bearerToken })
                .then(function(jsondata) {
                    $rootScope.userData.locale = retrieveLocale();

                    // Set locale via Factory
                    var currentLocale = CurrentLocaleFactory;
                    currentLocale.locale = $rootScope.userData.locale;

                    $rootScope.userData.firstname = (jsondata.firstname == null) || (jsondata.firstname == null) ? '' : jsondata.firstname;
                    $rootScope.userData.lastname = (jsondata.lastname == null) || (jsondata.lastname == null) ? '' : jsondata.lastname;
                    var avatar = username.split('@')[0].toLowerCase();

                    $http.get('assets/json/avatar.json')
                    .then(function(res) {

                        $rootScope.userData.gravatarLink = res.data.gravatarLink;
                        if (persistData === true) {
                            saveData();
                        }
                        if (typeof successCallback === 'function') {
                            successCallback();
                        }
                    }, function() {
                        $rootScope.userData.gravatarLink = "assets/img/noface.png";
                        if (persistData === true) {
                            saveData();
                        }
                        if (typeof successCallback === 'function') {
                            successCallback();
                        }
                    })
            })
        }, function(data) {
            if (typeof errorCallback === 'function') {
                if (data.error_description) {
                    errorCallback(data.error_description);
                } else {
                    errorCallback(data.data.message);
                }
            }
        })
};

1 个答案:

答案 0 :(得分:1)

从函数中返回promise:

 //First return
 return TokenService.one('authentokens').customPOST({
     'email': username,
     'password': password
 }, '', {
     app: 'baam'
 }).then(function(data) {
     /* ... */
     // Second return inside the success handler
     return TokenService.one('users').customGET($rootScope.userData
         .resourceId, {
             'token': $rootScope.userData.bearerToken
         }).then(function(jsondata) {
         /* ... */
     })
 })

然后,您的函数将返回一个将在两个异步调用都返回后解析的承诺。

如果排序不重要,您还可以使用$q.all(arrayOfPromises),它返回一个承诺,当数组中的所有承诺都返回时,它将被解析。