0

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

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?

1
  • why do you want to show your data when it reached at certain time while doing the request? What if the data takes longer or less than your timeout? you can use catch to see if your request fails, .catch(function(response){}) then process it there or do whatever when it sees the request has failed. Commented Jun 29, 2017 at 23:48

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.