AngularJS $resource 使用超时中止异步函数请求

AngularJS $resource Abort Async Function Request using a Timeout

您好,我正在寻找一种中止 .$save() 请求的方法。我的资源对象目前有一个以毫秒为单位的超时,但是它没有像我预期的那样工作。超时将在 x 毫秒后触发 curCacheObj.$save 上的错误响应,但它实际上并没有中止 .$save() 方法,它仍然 post 到数据库!所以我正在考虑按照以下方式做一些事情:

$timeout(function() {
     // abort .$save() function here
}, 30000);

但是我似乎找不到真正中止请求的方法。

目前我有以下代码(简化):

app.factory('Post', function($resource) {
  return $resource('http://my_endpoint_here/post', {}, {save: {
        method: 'POST',
        timeout: 5000
        }
   });
});

app.service('scService', function ($window, Post, $cordovaProgress, $cordovaDialogs, $timeout) {
                 if (postCount > 0) {
                    $cordovaProgress.showSimple(false);
                    curCacheObj.$save(function (response) {
                            console.log("Post " + postCount + " sent!");
                        }, function (response) {
                              $cordovaProgress.hide();
                              console.log(curCacheObj);
                              $window.location.href= 'index.html';
                              return;
                        }).then(function() {
                            window.localStorage.removeItem("post" + postCount);
                            postCount --;
                            window.localStorage.setItem("localPostCount", postCount);
                            $cordovaProgress.hide();
                            console.log("this just ran");
                            scService.sendCache();
                        });
                }
                else {              
                    $cordovaProgress.showSuccess(false, "Success!");
                    $timeout(function() {
                      $cordovaProgress.hide();
                      $window.location.href= 'index.html';
                    }, 1500);
                }
});

原来我通过将超时设置为 50 毫秒造成了 'artificial' 错误。我没有意识到 Web 服务端点如何响应传入请求。我通过连接不良的测试弄清楚了这一点。在连接良好的情况下,每次都会成功发送 .$save() 请求。在 .$save() 发送的那一刻,无论超时如何,Web 服务都会完成其操作。它所知道的只是一个请求刚刚进来,所以它完成了它的任务并且 returns 一个成功的响应。然后超时将在 app.js(50 毫秒内)内触发,我的错误逻辑将 运行 通过。

修复这个 'error' 只需要设置适当的 60 秒超时。

app.factory('Post', function($resource) {
  return $resource('http://my_endpoint_here/post', {}, {save: {
        method: 'POST',
        timeout: 60000 // prev 50ms during testing
        }
   });
});