简体   繁体   English

AngularJS在完成另一个函数后执行一个函数

[英]AngularJS execute a function after the completion of another function

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. 在最后一行中,您可以看到我首先调用fail()函数,然后_goback()函数。 I want that _goback() starts when fail() finish, but fail() contains a timeout , and I think that for this reason the function is asynchronous. 我希望_goback()fail()完成时启动,但fail()包含超时 ,我认为由于这个原因,该函数是异步的。 I don't understand how I can do 我不明白我该怎么做

Use the $timeout service to create a promise: 使用$ timeout服务创建一个promise:

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 use the .then method to wait: 然后使用.then方法等待:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM