异步请求与服务器进程/通知进程、服务器、通知

2023-09-14 23:07:51 作者:此名帅到加载失败

我有设置,将执行异步HTTP请求服务的问题。

I am having problem with setting up a service that will perform asynchronous http request.

背景

我有一个后端端点 /cars.json 当你点击这个端点首次后台作业,这将获取所有信息会启动汽车。服务器然后返回响应状态为200:

I have a backend endpoint /cars.json When you hit this endpoint for the first time the background job which will fetch all the cars information gets started. Server then returns response with status 200:

{"status":"started", "percentage_completion":0, "data":null, "error":null}

连续请求该端点将继续使用更新的 percentage_completion 的

{"status":"started", "percentage_completion":45, "data":null, "error":null}
{"status":"started", "percentage_completion":90, "data":null, "error":null}

最后请求到端点将返回:

Finally the request to the endpoint will return:

{"status":"finished", "percentage_completion":100, "data": {...}, "error":null}

和幸福的日子我有一个数据,我可以把它添加到 $范围

and happy days I have a data and I can add it to the $scope.

但我有很难让我的头周围的承诺和做事方式的角度...

But I am having hard time to get my head around the promises and angular way of doing things...

我已经上调是这样的:

   var dashboard = angular.module('dashboard', [                                                                                       
      'templates'                                                                                                                     
    ]);                                                                                                                                 

   dashboard.controller('dashboardController', ['carsService', '$scope',                                                          
        function(carsService, $scope){                                                                                             
          $scope.test = "Loading...";                                                                                                   
          carsService.get()                                                                                                        
            .then(function(response){                                                                                                   
              $scope.test = response.data;                                                                                              
            });                                                                                                                         
        }]                                                                                                                              
   );                                                                                                                                  

    dashboard.factory('carsService', ['$http', function($http){                                                                    
      var get = function(){                                                                                                             
        return $http.get('/cars.json');                                                                                            
      };                                                                                                                                
      return {                                                                                                                          
        get: get                                                                                                                        
      };                                                                                                                                
    }]);

它发送一个请求到服务器,并在与第一响应,说明该作业已被启动的范围更新测试。当我刷新页面几秒钟后,我得到了正确的数据和状态完成更新测试。

It sends a single request to the server and updates the test on the scope with the first response stating the job has been started. When I refresh the page after few seconds I get the test updated with a correct data and the finish status.

这将是一个最好的办法,棱角分明的方式:)用承诺和东西有服务和控制器自动做到这一点。

What would be a best way, angular way:) with promises and stuff to have the service and controller do it automatically.

第一件事是使用 $间隔或类似的东西,并定期重新发送。然后从(成功)的要求,但也许有更好的方法

First thing that comes to my head is to use a $interval or something similar and periodically resend the request from .then(success) but maybe there is a better way.

角文件说,一些有关进度/通知希望,但是在现阶段,我不知道如何把它

Angular documentation says something about progress/notify promise but at the moment I have no idea how to wire it in.

很显然,我不完全理解的那一刻,我刚刚介绍给他们的承诺 - 你可以分享一些技巧/关于如何处理异步请求的资源使用的角度

Obviously I don't fully understand the promises at the moment, I just got introduced to them - can you share some tips/resources on how to deal with asynchronous requests using angular?

推荐答案

我想你可以使用嵌套的承诺取得进展通知:

I guess you can use nested promise to achieve progress notify:

function get(){

    var defer = $q.defer();

    (function fetchData(){

        $http.get('/cars.json').then(function(result){
            if(result.status === 'started'){
                fetchData();
                defer.notify(result);
            }else if(result.status === 'finished'){
                defer.resolve(result);
            }
        }, function(err){
            defer.reject(err);
        })

    })()

    return defer.promise;
}

当你调用获得(),它首先调用 fetchData 从服务器请求数据。当 fetchData 解决,检查 result.status ,如果状态还没有完成,调用 fetchData 再次通知outter延迟,否则,解决outter与最终结果推迟

when you call get(), it first call fetchData to request data from server. When fetchData resolved, check result.status, if status is not finished, call fetchData again and notify outter defer, otherwise, resolve outter defer with final result

//in controller
carService.get().then(
    function(finalData){ $scope.test = finalData }, 
    function(err){ ... }, 
    function(notifyData){ $scope.test = notifyData }
}