JSFiddle - React, Tailwind, and code Playground
HTML
<div ng-app="" ng-controller="MyController"></div>
JavaScript
function MyController($q) {
function retryAction(action, numTries) {
return $q.when().then(action)
.catch(function (error) {
if (numTries <= 0) {
throw new Error("Maximum tries exceeded: " + (error.message || ""));
}
return retryAction(action, numTries - 1);
});
}
var throwErrorTwoTimes = makeMultipleThrowFunction(2);
retryAction(function () { return throwErrorTwoTimes(); }, 5)
.then(function (result) {
console.log(result);
// do something with result
});
// Example of a function that throws
// several times before ultimately succeeding
function makeMultipleThrowFunction(count) {
var thrownCount = 0;
return function () {
if (thrownCount < count) {
thrownCount++;
throw new Error("Throwing Error " + thrownCount);
}
// not necessary to use $q here; just throwing promises
// into the mix
return $q.when("Success!");
}
};
}