Here's an ES5 implementation of a retry wrapper function that doesn't use Promises, async, or await:
function retryWrapper(options, fn) {
var maxRetries = options.maxRetries || 3;
var delay = options.delay || 1000;
var retryCount = 0;
function execute() {
try {
fn(function(err, result) {
if (err) {
if (retryCount < maxRetries) {
retryCount++;
console.log('Retry attempt ' + retryCount + ' in ' + delay + 'ms');
setTimeout(execute, delay);
} else {
console.log('Max retries reached. Giving up.');
options.onError(err);
}
} else {
options.onSuccess(result);
}
});
} catch (err) {
if (retryCount < maxRetries) {
retryCount++;
console.log('Retry attempt ' + retryCount + ' in ' + delay + 'ms');
setTimeout(execute, delay);
} else {
console.log('Max retries reached. Giving up.');
options.onError(err);
}
}
}
execute();
}
// Usage example:
retryWrapper({
maxRetries: 3,
delay: 1000,
onSuccess: function(result) {
console.log('Operation succeeded:', result);
},
onError: function(err) {
console.error('Operation failed:', err);
}
}, function(callback) {
// This is the function to retry
// Simulate an operation that might fail
var success = Math.random() > 0.7; // 30% chance of success
if (success) {
callback(null, 'Success result');
} else {
callback(new Error('Operation failed'));
}
});
Key Features:
- ES5 compatible - Uses only ES5 features
- Callback-based - Uses traditional error-first callbacks
- Configurable - Allows setting max retries, delay between retries
- Error handling - Provides success and error callbacks
- No Promises - Uses setTimeout for delays and manual retry logic
The wrapper will automatically retry the function up to the specified number of times if it fails, with a delay between attempts. If all retries are exhausted, it will call the error handler.