ES5 Retry Wrapper without Promises/Async/Await
Here's a retry wrapper function in ES5 that doesn't use Promises, async/await, or any modern JavaScript features:
/**
* Retry wrapper function
* @param {Function} fn - The function to retry
* @param {Object} [options] - Configuration options
* @param {number} [options.maxRetries=3] - Maximum number of retry attempts
* @param {number} [options.delay=1000] - Delay between retries in milliseconds
* @param {Function} [options.shouldRetry] - Function to determine if a retry should occur
* @param {Function} [options.onRetry] - Callback when a retry occurs
* @param {Function} [options.onError] - Callback when all retries fail
* @returns {*} The result of the function or the last error
*/
function retryWrapper(fn, options) {
var opts = options || {};
var maxRetries = opts.maxRetries || 3;
var delay = opts.delay || 1000;
var shouldRetry = opts.shouldRetry || defaultShouldRetry;
var onRetry = opts.onRetry || function() {};
var onError = opts.onError || function() {};
var attempts = 0;
var lastError;
function defaultShouldRetry(error) {
return attempts < maxRetries;
}
function attempt() {
try {
var result = fn();
return result;
} catch (error) {
lastError = error;
attempts++;
if (shouldRetry(error, attempts)) {
onRetry(error, attempts);
setTimeout(function() {
attempt();
}, delay);
} else {
onError(error, attempts);
return lastError;
}
}
}
return attempt();
}
Usage Example
// Example function that might fail
function unreliableFunction() {
if (Math.random() > 0.7) {
return "Success!";
}
throw new Error("Temporary failure");
}
// Using the retry wrapper
var result = retryWrapper(unreliableFunction, {
maxRetries: 5,
delay: 2000,
shouldRetry: function(error, attempt) {
console.log("Attempt " + attempt + " failed: " + error.message);
return attempt < 5; // Retry up to 5 times
},
onRetry: function(error, attempt) {
console.log("Retrying... attempt " + attempt);
},
onError: function(error, attempt) {
console.log("All retries failed after " + attempt + " attempts");
}
});
console.log("Final result:", result);
Key Features:
- Pure ES5 implementation (no Promises, async/await)
- Configurable retry count and delay
- Customizable retry conditions
- Callback hooks for retry events and final failure
- Returns either the successful result or the last error
The wrapper will keep trying to execute the function until either:
- It succeeds, or
- The shouldRetry function returns false, or
- The maximum retry count is reached