angularjs使用interval实现异步轮询

        // 发起请求的function,服务器收到请求会启动一个任务,response中包含一个任务ID,比如用ticket_id字段表示。
        $scope.run_test = function() {
            $scope.running = true;
            $http.get('/run-test', {
                      params: {
                          'target' : $scope.data_psm.target,
                      }})
                      .success(function(resp){
                        $scope.ticket_id = resp['ticket_id'];  // 获取任务ID用于之后轮询
                        $scope.checkStatus();  // 开始轮询
                      }).error(function(resp){
                        $scope.reg_test_result = "ERROR";
                        if ('process' in resp['log']) {
                            $scope.reg_test_result = resp['log']['process'].join("\n");
                        }
                        $scope.running = false;
                      });
        };

        var stop;  // 定义一个stop变量,用于存储interval
        $scope.checkStatus = function() {
            // Don't start a new check_status if we are already checking
            if ( angular.isDefined(stop) ) return;  // 避免重复定义
            stop = $interval(function() {  // 轮询请求,根据ticket id进行轮询
                $http.get(
                    '/check-status',
                    {
                        params : {
                            "ticket_id":$scope.ticket_id
                        }
                    }
                ).success(function(resp){
                    $scope.result = resp;
                    // training
                    if ('process' in resp['log']) {  // 从response中获取一些业务信息
                        $scope.process = resp['log']['process'].join("\n");
                        $scope.reg_test_result = $scope.process
                            + "\n-----fail list-----\n"
                            + resp['fail_list'].join("\n")
                    }

                    if (resp['status'] != "running") {  // 如果ticket id对应的任务状态不是running,那么就停止轮询
                        $scope.running = false;
                        $scope.stopCheckStatus();
                        return;
                    }
                    $scope.checkStatus(resp['ticket_id']);  // 继续轮询,类似一种递归策略

                }).error(function(resp){
                    $scope.process = resp;  // 获取一些业务信息
                    $scope.stopCheckStatus();  // 遇到error也要停止轮询
                    $scope.running = false;  
                });
            }, 2000);
        };

        $scope.stopCheckStatus = function() {  // 定义停止轮询的function,执行interval.cancel
          if (angular.isDefined(stop)) {
            $interval.cancel(stop);
            stop = undefined;
          }
        };

        $scope.$on('$destroy', function() {  // 确保页面退出时,interval被销毁
          // Make sure that the interval is destroyed too
          $scope.stopCheckStatus();
        });

如何在服务器实现异步任务呢?以Python中的Flask+Thread为例:https://www.cnblogs.com/CheeseZH/p/12444086.html

posted @ 2020-03-08 18:31  ZH奶酪  阅读(812)  评论(0编辑  收藏  举报