Reputation: 2464
I need to send multiple get requests(required) one by one. When the count is 2-3, it works fine, but with almost 6 HTTP Get requests, sometimes some of them fails and give Internal Sever Error(500)
. Opening the error link in new tab gives required results.
So there is nothing wrong from server side.
I'm facing this problem both in : localhost
and production
.
How to deal with this situation from client side?
I've tried:
NodeJS + SocketIO
to send data from server without asking. [with so much data if socket keeps writing till 60 sec. socket re-registers & restarts from beginning.]Angular + NGResource
. [internally uses http get. issue persists.]Angular + Restangular Lib
. [internally uses http get. issue persists.]Please suggest how do I know what the problem is. Then only I can think of a solution.
Thnx!!
Upvotes: 2
Views: 486
Reputation: 1633
Here's a function in which you can wrap your HTTP calls. It will repeat the call until it passes. Beware! If the HTTP call fails 100% of the time (for example, malformed URL), then the function will not stop (In testing, the function was called >70,000 times. Apparently there is no recursion limit with promises). For that case, I've included a limited version of the function that stops after n attempts.
var persistentRequest = function(requestFn) {
var deferred = $q.defer();
requestFn().then(function() {
deferred.resolve();
}, function() {
persistentRequest(requestFn).then(
function() {
deferred.resolve();
}
);
});
return deferred.promise;
}
var persistentRequestLimited = function(requestFn, n) {
var deferred = $q.defer();
if (n <= 0) {
deferred.reject('Did not complete in given number of tries');
} else {
requestFn().then(function(data) {
deferred.resolve(data);
}, function() {
persistentRequestLimited(requestFn, n-1).then(
function(data) {
deferred.resolve(data);
},
function(rejection) {
deferred.reject(rejection);
}
);
});
}
return deferred.promise;
}
For example, use it like:
persistentRequest(function() {
return $http.get('/myurl');
});
persistentRequestLimited(function() {
return $http.get('/myurl');
}, 10);
Don't forget to inject $q into your controller/service/etc.
Upvotes: 1