AngularJS executes a function after completing another function

I execute a function that calls two functions sequentially in order to start the second function, first you need to complete the first. But this does not happen, possibly because the first function is asynchronous. I read that I need to use a "promise . " I tried it differently, but it does not work. So I rewrote the function, as I originally wrote:

function fail() { 
    // Get the snackbar DIV
    var x = document.getElementById("snackbar")

    // Add the "show" class to DIV
    x.className = "show";

    // After 3 seconds, remove the show class from DIV
    setTimeout(function(){ x.className = x.className.replace("show", "");}, 3000);   

}

function _goback(){
    $location.url('/app/dispensers');
}    

//Check if the item is still available (if nobody bought it)
function _checkavailability(response){
    if (response.data == ""){
              console.log("Accesso non autorizzato")
    }
    $scope.infoproductbyid = response.data;
    if($scope.infoproductbyid.purchaseTime == null){
        console.log("Item disponibile");
        //if the item is available, it possible to proceeds to checkout
        $location.url('/app/notregcheckout');
    }
    else{
        console.log("Spiacente, item non più disponibile");
      //  localStorage.clear("tokenidproduct");
        //_showSB();  
        fail();
        _goback();
    }    
}               

, fail() , _goback() - . , _goback() , fail() , fail() -, , . ,

+4
1

$timeout service, :

function fail() { 
    // Get the snackbar DIV
    var x = document.getElementById("snackbar")

    // Add the "show" class to DIV
    x.className = "show";

    // After 3 seconds, remove the show class from DIV
    var promise = $timeout(function() {
      x.className = x.className.replace("show", "");
    }, 3000);

    //RETURN promise   
    return promise;
}

.then :

fail().then(function() {
    _goback();
});
+4

Source: https://habr.com/ru/post/1678510/


All Articles