2015-10-15 121 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; 
            } 
           }]) 
    
实现