Reputation: 73
In my app I'm getting list of hosts provided by user in textarea field form and insert them into my database using HTTP POST to API.
All works fine until the list exceeds 2.5k hosts when I get net::ERR_INSUFFICIENT_RESOURCES error. I read that it is related to some Chrome limitations.
How can I overcome this limitation? I was trying to split the list to the bunches and introduce some delay between them but it doesn't work (it seems all bunches are started asynchronously in the same time).
Controller:
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!');
}
}
}
Service:
.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
});
}
Upvotes: 1
Views: 1622
Reputation: 48968
Instead of executing the requests in parallel, chain them:
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;
}
The reducer starts with a promise of an empty array. Each iteration of the reducer chains another HTTP promise to the array of responses. The result is a promise that resolves to an array of responses. By chaining the HTTP requests, they are executed sequentially instead of in parallel.
Upvotes: 2