2017-06-04 63 views
4

完成后执行功能我执行调用两个函数顺序的功能,运行第二个函数应首先完成第一个。但是这不会发生,也许是因为第一个函数是异步的。我读到,我需要使用“承诺”我试过了,用不同的方式,但它不起作用。所以我改写了功能我最初写的:AngularJS另一功能

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

在最后行,你可以看到,我呼吁第一fail()功能,以及第二_goback()功能。我想这_goback()开始时fail()完成,但fail()包含超时,我认为这个原因该函数是异步的。我不明白,我该怎么办

+0

你可以把_goback();函数内失效()函数超时等setTimeout函数(函数(){ x.className = x.className.replace( “节目”, “”); _goback();} ,3000); – Anupam

+0

我已经尝试过这种方式; '的setTimeout(函数(){x.className = x.className.replace( “节目”, “”); _goback();},3000);' 但在这种情况下_goback()不工作 –

+0

第二功能不会以这种方式 –

回答

3

使用$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(); 
}); 
+0

'$超时未定义' –

+0

好吧,我注入$超时控制器的功能: .controller(“CartController”,function($ scope ,$ filter,$ http,$ location,$ stateParams,restService,$ timeout){ 谢谢,现在工作正常 –