/**
* Wraps a function that processes a JSON payload with retry logic.
*
* @param {function} fn The function to execute with retry. Should accept a JSON payload as input.
* @param {number} maxRetries The maximum number of retry attempts.
* @param {number} delayMs The delay in milliseconds between retries.
* @returns {function} A function that takes a JSON payload and executes the wrapped function with retry.
*/
function retryWithDelay(fn, maxRetries, delayMs) {
let retryCount = 0;
/**
* Executes the wrapped function with retry logic.
* @param {object} payload The JSON payload to process.
* @returns {Promise<any>} A promise that resolves with the result of the function or rejects if all retries fail.
*/
return async function (payload) {
return new Promise((resolve, reject) => {
function attempt() {
fn(payload) // Execute the original function
.then(resolve)
.catch(err => {
retryCount++;
if (retryCount >= maxRetries) {
reject(err); // Reject the promise if max retries reached
return;
}
setTimeout(() => {
attempt(); // Retry after the specified delay
}, delayMs);
});
}
attempt(); // Start the first attempt
});
};
}
Add your comment