0

I got a perfectly working service

this.getcustomers= function() { 
                        var deferred = $q.defer();
                        $http({
                            method: 'GET',
                            url: 'api/customers'
                        }).then(function success(data) {
                            deferred.resolve(data.data);
                          }, function error(error) {
                            deferred.reject(error);
                          });
                        return deferred.promise;
                    };

How do i add a timeout to the above. I tried samples from stackoverflow but nothing is working I need the request to keep trying for 5000 ms and show an error when that time passes. Adding timeout : timeout|promise does not work with me.

Any ideas?

user3052526
  • 681
  • 10
  • 24

2 Answers2

1

What you're looking for is a retry mechanism, rather than a timeout. Timeout means "perform an action after X time", in JS anyway.

See the answer here, should be what you're looking for:
AngularJS service retry when promise is rejected

Community
  • 1
  • 1
Artless
  • 4,522
  • 1
  • 25
  • 40
  • That actually worked, but how can i keep on trying for `X` number of seconds? – user3052526 Oct 14 '15 at 09:38
  • Well, instead of checking number of retries, compare times. Save a timestamp of the first attempt. You can use `Date.now()` to get a unix timestamp. Then keep retrying until `Date.now() - startTime` is greater than whatever you want to limit it to. – Artless Oct 14 '15 at 09:49
0

Here is working link of jsfiddle

function httpRequestHandler () {
            var timeout = $q.defer(),
                result = $q.defer(),
                timedOut = false,
                httpRequest;

            $timeout(function () {
                timedOut = true;
                timeout.resolve();
            }, (1000 * $scope.timeout));

            httpRequest = $http({
                method : 'post',
                url: '/echo/json/',
                data: createData(),
                cache: false,
                timeout: timeout.promise
            });

            httpRequest.success(function(data, status, headers, config) {
                result.resolve(data);
            });

            httpRequest.error(function(data, status, headers, config) {
                if (timedOut) {
                    result.reject({
                        error: 'timeout',
                        message: 'Request took longer than ' + $scope.timeout + ' seconds.'
                });
                } else {
                    result.reject(data);
                }
            });

            return result.promise;
        }
Gaurav Sachan
  • 320
  • 1
  • 10