Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I am using some functions that send $http async request to server side.i want to call same current function after relogin user if response is "notlogin". I think i need to use promise but how?

$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;
            }
});
}
share|improve this question
3  
What is function B? – dfsq Aug 23 at 15:35
    
it is login function... – Mehdi Rostami Aug 23 at 17:20

2 Answers 2

up vote 0 down vote accepted

Try make $scope.B() as promise (It's something asynchronous, I understand correctly?);

$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();
});
share|improve this answer
    
This is an anti-pattern if scope.B already is using $http and can simply return that promise – charlietfl Aug 23 at 15:56
    
i am new in angular ... can you please make answer clear?i edited question. – Mehdi Rostami Aug 23 at 16:09
    
i tested this but .then() didn't fire .i used $scope.$apply(function() { deffer.resolve(thing); }); but not worked – Mehdi Rostami Aug 23 at 17:08
    
Thanks @user3335966 i added settimeout to your solution and it worked perfectly. – Mehdi Rostami Aug 23 at 17:42

You can return success callback of $scope.B() by just returning the $http call

$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",...});
 };
share|improve this answer
    
in my code i return boolean instead of $http and because of async call, the condition for call function A not working. it seems no difference between bool or $http return. – Mehdi Rostami Aug 23 at 16:36

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.