AngularJS service retry when promise is rejected

后端 未结 5 2226
Happy的楠姐
Happy的楠姐 2020-12-13 11:06

I\'m getting data from an async service inside my controller like this:

myApp.controller(\'myController\', [\'$scope\', \'AsyncService\',
function($scope, As         


        
5条回答
  •  星月不相逢
    2020-12-13 11:14

    Following this article Promises in AngularJS, Explained as a Cartoon

    you need to retry only when the response comes under 5XX category

    I have written a service called http which can be called by passing all http configs as

     var params = {
      method: 'GET',
      url: URL,
      data: data
     }
    

    then call the service method as follows:

       .http(params, function(err, response) {});
    

    http: function(config, callback) {
      function request() {
        var counter = 0;
        var queryResults = $q.defer();
    
        function doQuery(config) {
          $http(config).success(function(response) {
            queryResults.resolve(response);
          }).error(function(response) {
            if (response && response.status >= 500 && counter < 3) {
              counter++;
              console.log('retrying .....' + counter);
              setTimeout(function() {
                doQuery(config);
              }, 3000 * counter);
            } else {
              queryResults.reject(response);
            }
          });
        }
        doQuery(config);
        return queryResults.promise;
      }
      request(config).then(function(response) {
        if (response) {
          callback(response.errors, response.data);
        } else {
          callback({}, {});
        }
      }, function(response) {
        if (response) {
          callback(response.errors, response.data);
        } else {
          callback({}, {});
        }
      });
    }

提交回复
热议问题