【问题标题】:AngularJS catch ideling promiseAngularJS 抓住了空想的承诺
【发布时间】:2016-07-27 22:18:16
【问题描述】:

我目前正在尝试编写某种配置服务。该服务提供到另一台服务器的路径。将使用接收到的路径通过 ping 功能测试该路径的有效性。如果路径指向不存在的服务器,则不会有任何承诺,并且由于通常应该在使用代码中的 .then(function (data){ }); 交付承诺后发生的操作而导致整个应用程序卡住。
那么有没有办法捕捉这样一个缺失/未决的承诺以防止冻结我的应用程序?

这是 AngularController 中的代码(由按钮触发)

applicationPingService.ping(path)
.then(function(successStatus){
    if(successStatus == true){

        //Some code here

    }
    else{
        //Some other code here
    }
});

这是被调用的服务。
它采用http://localhost:8080 之类的路径并尝试访问blank.html 页面以检查服务器是否已启动的状态代码。

app.service('applicationPingService', ['$http', '$q', 'globalValue', function($http, $q, globalValue) {

    this.ping = function(path)
    {
        return $http({
            method: "GET",
            url: path + "/blank.html" 
        }).then(function(response)
        {
            if(response.status == 200)
            {
                return true;
            }
            else{
                return false;
            }

        });
    };
}]);

这只是一个例子,但我也想知道一种通用的方法来捕获空闲和丢失的承诺

提前致谢

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    我在一个很好的tutorial page for promises找到了这个例子:

    var jqDeferred = jQuery.ajax('http://localhost/blank.html');
    
    jqDeferred.then(function(response, statusText, xhrObj) {
      alert('success');
    }, function(xhrObj, textStatus, err) {
      alert('error');
    });
    

    有时服务器响应时间过长。然后你可以使用自己的超时时间并使用它:

    Promise.race(array);做出承诺,只要任何项目都履行 满足或拒绝任何项目拒绝,以发生者为准 首先。

    【讨论】:

      【解决方案2】:

      Angular 1.5 中有 $q.race 方法可以做到这一点:

      var timeoutPromise = $timeout(() => $q.reject('timeout'), 5000);
      
      $q.race([pingPromise, timeoutPromise]]).then(...);
      

      【讨论】:

        猜你喜欢
        • 2016-10-25
        • 1970-01-01
        • 2020-01-16
        • 1970-01-01
        • 2019-05-07
        • 2014-10-05
        • 2012-12-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多