AngularJS execute a function after the completion of another function

Viewed 4926

I execute a function that calls two functions sequentially, to run the second function should first finish the first one. But this does not happen, perhaps because the first function is asynchronous. I read that I need to use "promise" I tried it, in different way, but it doesn't works. So I rewrote the function as I initially 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's possible to proceeds to checkout
        $location.url('/app/notregcheckout');
    }
    else{
        console.log("Spiacente, item non più disponibile");
      //  localStorage.clear("tokenidproduct");
        //_showSB();  
        fail();
        _goback();
    }    
}               

In the last rows, you can see that I call fail() function for first, and _goback() function for second. I want that _goback()starts when fail()finish, but fail() contains a timeout, and I think that for this reason the function is asynchronous. I don't understand how I can do

1 Answers
Related