1. /**
  2. * Retries a function with manual retry logic.
  3. * @param {function} fn The function to retry. Should accept user data as input.
  4. * @param {number} maxRetries The maximum number of retry attempts.
  5. * @param {number} delayMs The delay in milliseconds between retries.
  6. * @param {function} [dataPrep] Optional function to prepare user data before execution.
  7. * @param {function} [dataCleanup] Optional function to clean up user data after execution.
  8. * @returns {Promise<any>} A promise that resolves with the result of the function if successful, or rejects if all retries fail.
  9. */
  10. async function retryOperation(fn, maxRetries, delayMs, dataPrep = (data) => data, dataCleanup = (data) => data) {
  11. let attempts = 0;
  12. while (attempts < maxRetries) {
  13. attempts++;
  14. try {
  15. // Prepare data before execution if a prep function is provided.
  16. const preparedData = dataPrep(await fn());
  17. // Execute the function.
  18. return preparedData; // Resolve the promise with the result.
  19. } catch (error) {
  20. if (attempts === maxRetries) {
  21. // All retries failed, reject the promise.
  22. throw error;
  23. }
  24. // Wait before retrying.
  25. await new Promise(resolve => setTimeout(resolve, delayMs));
  26. }
  27. }
  28. }
  29. // Example Usage (Illustrative - replace with your actual data and function)
  30. // async function fetchData(data) {
  31. // // Simulate an API call that might fail.
  32. // if (Math.random() < 0.5) {
  33. // throw new Error("API request failed");
  34. // }
  35. // return "Data from API";
  36. // }
  37. // async function main() {
  38. // try {
  39. // const result = await retryOperation(fetchData, 3, 1000);
  40. // console.log("Operation successful:", result);
  41. // } catch (error) {
  42. // console.error("Operation failed after multiple retries:", error);
  43. // }
  44. // }
  45. // main();

Add your comment