Alf*_*tri 4 javascript asynchronous function promise 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();
}
}
Run Code Online (Sandbox Code Playgroud)
在最后一行中,您可以看到我先调用fail()函数,然后调用函数_goback().我希望_goback()在fail()完成时启动,但fail()包含超时,我认为由于这个原因,该函数是异步的.我不明白我该怎么做
使用$ 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;
}
Run Code Online (Sandbox Code Playgroud)
然后使用该.then方法等待:
fail().then(function() {
_goback();
});
Run Code Online (Sandbox Code Playgroud)