gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:28:21 26 4
gpt4 key购买 nike

我执行一个按顺序调用两个函数的函数,运行第二个函数应该首先完成第一个函数。但这并没有发生,也许是因为第一个函数是异步的。我读到我需要使用 "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
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() 包含一个超时,并且我认为由于这个原因,函数是异步的。我不明白我该怎么办

最佳答案

使用 $timeout service创建 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方法等待:

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

关于javascript - AngularJS 在另一个函数完成后执行一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44356936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com