2016-07-27 143 views
1

我目前正在嘗試編寫某種配置服務。該服務提供了到另一臺服務器的路徑。該路徑將通過使用接收路徑的ping功能進行有效性測試。如果路徑指向一個不存在的服務器,則不會有任何承諾,並且整個應用程序由於在代碼中使用.then(function (data){ });交付承諾後通常應發生的操作而受阻。
那麼有沒有辦法如何捕獲這樣的失蹤/未決的承諾,以防止凍結我的應用程序?AngularJS catch理想承諾

這裏是在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; 
      } 

     }); 
    }; 
}]); 

這只是一個例子,但我也想知道一個普遍的方式如何捕捉空轉和失蹤承諾

在此先感謝

回答

0

我發現這個例子中,在一個非常好的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);做出一個承諾,只要任何項目 履行完成,或拒絕任何項目拒絕,以先發生者爲先 。

0

有在角1.5 $q.race方法,做的是:

var timeoutPromise = $timeout(() => $q.reject('timeout'), 5000); 

$q.race([pingPromise, timeoutPromise]]).then(...);