Mehdi Rostami Mehdi Rostami - 1 month ago 5
AngularJS Question

call function A in function A after success call function B in angular js


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

Answer

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