简体   繁体   English

超时处理程序在angularjs中返回数据

[英]timeout handler returning data in angularjs

Based on this answer I´m currently trying to create a service which returns data even if the request wasn't successful but it timed out. 基于此答案,我目前正在尝试创建一个即使请求未成功但超时的返回数据的服务。

this.getStatus = function()
    {
        var timeoutPromise = $timeout(function () {
            canceler.resolve();
            console.log("Timed out");
        },250);

        var canceler = $q.defer();

        $http.get("data.js", {timeout: canceler.promise} ).success(function(data){
          console.log(data);

          $timeout.cancel(timeoutPromise);

          return data;
        });
    };

This is how the Service with the $http request is called 这就是调用$http请求的服务的方式

var promises = [
    firstService.getStatus(),
    secondService.getStatus(),
    thirdService.getStatus()
];

$q.all(promises)
   .then(function (serviceResults) {
        //process Data in case of success
        console.log("Result First Service: "+ serviceResults[0]);
        console.log("Result Second Service: "+ serviceResults[1]);
        console.log("Result third Service: "+ serviceResults[2]);
    })
    .catch(function() {
        //process Mock data in case of Failure
    });

It should return either the data from the response if the request was successful or some placeholder data in case of a timeout. 如果请求成功,它应该从响应中返回数据,或者在超时的情况下返回一些占位符数据。
So how is it possible to return data if the request times out? 那么,如果请求超时,如何返回数据呢?

You could: 你可以:

this.getStatus = function()  {
    var deferred = $q.defer();
    var timeoutPromise = $timeout(function () {
        deferred.resolve(
          // MOCKED DATA HERE
        );
        console.log("Timed out");
    }, 250);

    $http.get("data.js", {timeout: canceler.promise} ).then(function(data){
      $timeout.cancel(timeoutPromise);
      deferred.resolve(data);
    }).catch(deferred.reject);

    return deferred.promise;
};

This way, if the request is successful it resolves with the response data. 这样,如果请求成功,它将使用响应数据进行解析。 If it timeouts, it resolves with the mocked data. 如果超时,它将使用模拟数据进行解析。 If another error happens before the timeout, it rejects the promise with the response error. 如果在超时之前发生另一个错误,它将拒绝带有响应错误的承诺。

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

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