简体   繁体   English

在递归承诺链中取消或停止$ timeout

[英]Cancel or stop a $timeout in a recursive promise chain

I have a service which checks for item status every 3 seconds. 我有一项服务,每3秒检查一次项目状态。 If the item status is ready, then returns the status string. 如果项目状态为就绪,则返回状态字符串。 Otherwise, use $timeout to wait for 3 seconds and try again. 否则,请使用$timeout等待3秒,然后重试。

My problem is I'd like to cancel or stop the recursive timeout when user triggers some events(ex: leave the current page), but I don't know how to do that. 我的问题是,当用户触发某些事件(例如:离开当前页面)时,我想取消或停止递归超时,但是我不知道该怎么做。

Service: 服务:

angular.module('app')
    .factory('ItemService', ItemService);

function ItemService($timeout, DataService) {
    var service = {
        checkStatus: checkStatus
    };

    function checkStatus() {
        return DataService.getItemStatus()
            .then(function(status){
                if (status === 'ready') {
                    return status;
                } else {
                    // the item is not ready. Check again after 3 seconds
                    return $timeout(function() {
                        return checkStatus();
                    }, 3000)
                }
            });
    }

}

Client: 客户:

angular.module('app')
    .controller('ItemCtrl', ItemCtrl);

function ItemCtrl($scope, ItemService) {
    ItemService.checkStatus()
        .then(function(status) {
            // do somethin when item is ready.
        });

    $scope.$on('destroy', function(){
        // Should stop the $timeout recursive, but don't know how..
    });
}

You should be able to cancel an angular timeout with 您应该可以通过取消角度超时

$timeout.cancel(promise)

So something like this should work: 所以这样的事情应该工作:

var promise = ItemService.checkStatus();
promise.then(function(status) {
        // do somethin when item is ready.
    });

$scope.$on('destroy', function(){
    if(typeof promise.then === 'function') {
        $timeout.cancel(promise);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM