【问题标题】:AngularJS execute a function after the completion of another functionAngularJS 在完成另一个函数后执行一个函数
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • '$timeout 未定义'
  • ok,我在控制器的函数中注入了$timeout:.controller("CartController", function($scope, $filter, $http, $location, $stateParams, restService, $timeout) { 谢谢,现在可以正常使用了
猜你喜欢
  • 2013-11-09
  • 1970-01-01
  • 2016-06-18
  • 1970-01-01
  • 1970-01-01
  • 2014-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多