2017-06-04 53 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){ 謝謝,現在工作正常 –