【问题标题】:AngularJS $resource Abort Async Function Request using a TimeoutAngularJS $resource 使用超时中止异步函数请求
【发布时间】:2015-09-17 16:18:28
【问题描述】:

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

$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);
                }
});

【问题讨论】:

    标签: angularjs asynchronous timeout abort


    【解决方案1】:

    原来我通过将超时设置为 50 毫秒来创建一个“人为”错误。我没有意识到 Web 服务端点如何响应传入的请求。我通过连接不良的测试来解决这个问题。连接良好时,每次都会成功触发 .$save() 请求。 .$save() 发送的那一刻,Web 服务将完成其操作而不管超时。它只知道一个请求刚刚进来,所以它完成了它的任务并返回一个成功的响应。然后超时将在 app.js 中触发(在 50 毫秒内),我的错误逻辑将运行。

    修复这个“错误”只需要设置一个适当的 60 秒超时时间。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多