2015-10-15 119 views
0

我有一些方法,爲同步任務執行。我使用$q.all解決所有的承諾後,保存的數據同步到本地數據庫。此應用程序允許用戶開始同步並取消正在進行的同步。所以我想取消所有的承諾執行或拒絕停止執行。這是我的示例代碼。 http://plnkr.co/edit/cMbFs0JZJjF1dC4IavDJ?p=preview終止角承諾執行

不知道如何阻止這些執行?或任何其他建議終止方法執行

回答

0

我不認爲這是一個殺法,因爲JS是基於單線程,事件驅動,u需要在控制器或範圍的工作標誌,檢查該標誌的每一個迴路,案例放棄,解決或拒絕

0

可以實現這樣的事情 -

  1. 創建一個全局請求陣列(pendingRequests)
  2. 定製的HTTPService創建HTTP調用Ajax調用(httpService.get(url,data
  3. cancelSync可以通過調用

       .service('pendingRequests', function() { 
            var pending = []; 
    
            this.cancelAll = function() { 
            angular.forEach(pending, function(p) { 
             p.canceller.resolve(); 
            }); 
            pending.length = 0; 
            }; 
           }) 
           .service('httpService', ['$http', '$q', 'pendingRequests', function($http, $q, pendingRequests) { 
            this.get = function(url,data) { 
            var canceller = $q.defer(); 
            pendingRequests.add({ 
             url: url, 
             canceller: canceller 
            }); 
            data.timeout = canceller.promise; 
    
            //Request gets cancelled if the timeout-promise is resolved 
            var requestPromise = $http.get(url,data); 
            //Once a request has failed or succeeded, remove it from the pending list 
            requestPromise.finally(function() { 
             pendingRequests.remove(url); 
            }); 
            return requestPromise; 
            } 
           }]) 
    
實現