- // 发起请求的 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
来源: http://www.bubuko.com/infodetail-3452836.html