【发布时间】:2017-06-04 17:32:31
【问题描述】:
我执行一个按顺序调用两个函数的函数,要运行第二个函数应该先完成第一个。但这不会发生,可能是因为第一个函数是异步的。我读到我需要使用 "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()finish 时启动,但fail() 包含超时,因此我认为该函数是异步的。我不明白我该怎么做
【问题讨论】:
-
你可以把_goback(); fail() 函数中的函数超时函数,例如 setTimeout(function() { x.className = x.className.replace("show", ""); _goback(); }, 3000);
-
这种方式我已经试过了; ' setTimeout(function(){ x.className = x.className.replace("show", ""); _goback();}, 3000);'但在这种情况下 _goback() 不起作用
-
第二个函数不是这样启动的
-
你有什么错误吗?
-
然后放另一个 setTimeout 像 setTimeout(function() { x.className = x.className.replace("show", ""); setTimeout(function(){ _goback(); },0 ) }, 3000);
标签: javascript angularjs function asynchronous promise