【问题标题】:Angularjs multiple HTTP POST requests causing net::ERR_INSUFFICIENT_RESOURCESAngularjs 多个 HTTP POST 请求导致 net::ERR_INSUFFICIENT_RESOURCES
【发布时间】:2020-05-30 01:55:38
【问题描述】:

在我的应用程序中,我正在获取用户以 textarea 字段形式提供的主机列表,并使用 HTTP POST 到 API 将它们插入到我的数据库中。

当我收到 net::ERR_INSUFFICIENT_RESOURCES 错误时,在列表超过 2.5k 主机之前一切正常。我读到它与某些 Chrome 限制有关。

我怎样才能克服这个限制?我试图将列表拆分为束并在它们之间引入一些延迟,但它不起作用(似乎所有束都是同时异步启动的)。

控制器:

AddHostsController.$inject = ['$scope', 'Authentication', 'App', 'Hosts', '$filter', '$timeout'];

function AddHostsController($scope, Authentication, App, Hosts, $filter, $timeout) {
    var vm = this;
    vm.submit = submit;
    ...some other staff...

    function submit() {
      var fulllist = [];
      vm.firstbunch = [];
      vm.secondbunch = [];
      fulllist = vm.host_list.split('\n');
      vm.firstbunch = fulllist.slice(0,1500);
      vm.secondbunch = fulllist.slice(1500,);

      $timeout(function() { vm.firstbunch.forEach(submitHost);}, 2000)
      .then(firstBunchSuccessFn, firstBunchErrorFn);

      function firstBunchSuccessFn(){
        vm.secondbunch.forEach(submitHost);
      }

      function firstBunchErrorFn(){
        console.log("Something went wrong!");
      }

      function submitHost(value, index, array){
        App.addhosts(...some args..., value).then(addHostsSuccessFn, addHostsErrorFn);

        function addHostsSuccessFn(response) {
        }

        function addHostsErrorFn(response) {
          console.error('Failure!');
        }
     }
}

服务:

.factory('App', App);

App.$inject = ['$http'];

function App($http) {
    var App = {
      addhosts: addhosts,
    };

    return App;

    function addhosts(...some other.., value) {

        return $http.post('/api/v1/hosts/', {
            ...some other...
            value: value
        });
    }

【问题讨论】:

    标签: javascript angularjs google-chrome http


    【解决方案1】:

    不要并行执行请求,而是将它们链接起来:

    var configArr = [/* Array of config objects */];
    var resultsArrPromise = configArr.reduce( reducerFn, $q.when([]) );
    
    responseArrPromise
      .then(function (responseArr) {
        responseArr.forEach( response => console.log(response.data) );
    }).catch(function (errorResponse) {
        console.log(errorResponse);
    }); 
    
    function reducerFn(acc, config) {
        var accArrPromise = acc.then(function(responseArr) {
            var httpPromise = $http(config);
            return $q.all( [...responseArr, httpPromise] );
        });
        return accArrPromise;
    }
    

    reducer 从一个空数组的 promise 开始。 reducer 的每次迭代都将另一个 HTTP 承诺链接到响应数组。结果是一个可以解析为一系列响应的承诺。通过链接 HTTP 请求,它们按顺序而不是并行执行。

    【讨论】:

    • 我通过在真正的网络服务器(nginx 和 gunicorn 与多个工作人员)而不是 django 开发网络服务器上运行代码来解决这个问题。响应时间急剧减少,性能问题消失了。
    猜你喜欢
    • 2019-11-15
    • 2017-08-24
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多