在角度js中成功调用函数B之后,在函数A中调用函数A.

时间:2015-08-23 15:16:39

标签: jquery angularjs xmlhttprequest async-await angular-http

  

我正在使用一些向服务器端发送$ http异步请求的函数。如果响应为“notlogin”,我想在重新登录用户后调用相同的当前函数。我想我需要使用承诺但是如何?

 $scope.A = function(){
    $http({..,async: "isAsync",...})
    .success(function (response) {
        if (response.d == "notlogin") {
            if ($scope.B())//call back login to refresh session
                $scope.A();//repeat request if login return true
        }
    });
};

 $scope.B= function () {

        $scope.userlogin_error = "wait...";
        $http({...,async: "isAsync",...}).success(function (response) {

            if (response.d == "True") {
                $scope.userlogin_error = "login success";
                $scope.user_islogin = true;

                return true;
            }
});
}

2 个答案:

答案 0 :(得分:0)

尝试将$ scope.B()改为promise(这是异步的,我理解正确吗?);

$scope.B = function(){
    var defer = $q.defer();
    if(something) {
        defer.resolve(data);
    } else {
        defer.reject(error);
    }
    return defer.promise;
};

$scope.B().then(function(data){
    $scope.A();
});

答案 1 :(得分:0)

只需返回$ http调用

,即可返回$ scope.B()的成功回调
$scope.A = function(){
   $http({..,async: "isAsync",...}).success(function (response) {
    if (response.d == "notlogin") {
        $scope.B().success(function(data){
           if(data.d == "True"){
                $scope.userlogin_error = "login success";
                $scope.user_islogin = true;
                $scope.A();
           }
        });
    }
   });
};

 $scope.B= function () {
   return $http({...,async: "isAsync",...});
 };