/**
* Retries a function with manual retry logic.
* @param {function} fn The function to retry. Should accept user data as input.
* @param {number} maxRetries The maximum number of retry attempts.
* @param {number} delayMs The delay in milliseconds between retries.
* @param {function} [dataPrep] Optional function to prepare user data before execution.
* @param {function} [dataCleanup] Optional function to clean up user data after execution.
* @returns {Promise<any>} A promise that resolves with the result of the function if successful, or rejects if all retries fail.
*/
async function retryOperation(fn, maxRetries, delayMs, dataPrep = (data) => data, dataCleanup = (data) => data) {
let attempts = 0;
while (attempts < maxRetries) {
attempts++;
try {
// Prepare data before execution if a prep function is provided.
const preparedData = dataPrep(await fn());
// Execute the function.
return preparedData; // Resolve the promise with the result.
} catch (error) {
if (attempts === maxRetries) {
// All retries failed, reject the promise.
throw error;
}
// Wait before retrying.
await new Promise(resolve => setTimeout(resolve, delayMs));
}
}
}
// Example Usage (Illustrative - replace with your actual data and function)
// async function fetchData(data) {
// // Simulate an API call that might fail.
// if (Math.random() < 0.5) {
// throw new Error("API request failed");
// }
// return "Data from API";
// }
// async function main() {
// try {
// const result = await retryOperation(fetchData, 3, 1000);
// console.log("Operation successful:", result);
// } catch (error) {
// console.error("Operation failed after multiple retries:", error);
// }
// }
// main();
Add your comment