I am having some trouble getting a retry function to work and was hoping for some assistance. I have a $resource that I want to have called until a success condition occurs or the maximum retries has been exceeded.
The issue I seem to be running into is that within my retry function I am calling another promise and that is where the condition would be checked. I could get the code to function as intended by removing the added promise and creating a default success condition after a few retries but I cannot figure out how to correctly add the new promise call into the function.
resource
is a stand-in for an Angular $resource which returns a $promise
My code is as follows:
resource.$promise.then(function (response) {
return keepTrying(state, 5);
}).then(function (response) {
}).catch(function (err) {
console.log(err);
});
And the keepTrying function:
function keepTrying(state, maxRetries, deferred) {
deferred = deferred || $q.defer();
resource.$promise.then(function (response) {
success = response;
});
if (success) {
return deferred.resolve(success);
} else if (maxRetries > 0) {
setTimeout(function () {
keepTrying(state, maxRetries - 1, deferred);
}, 1000);
} else if (maxRetries === 0) {
deferred.reject('Maximum retries exceeded');
}
return deferred.promise;
}
then
just adds a new callback. – Capitulumthen
doesn't change the underlying promise, it returns a new promise that will be resolved to the return value of your function. – Litigation