1. /**
  2. * Retries a function call with customizable retry options.
  3. *
  4. * @param {Function} fn The function to retry.
  5. * @param {object} options Optional retry configuration.
  6. * @param {number} options.retries The maximum number of retries. Defaults to 3.
  7. * @param {number} options.delay The delay between retries in milliseconds. Defaults to 1000.
  8. * @param {boolean} options.log The flag to log the retry attempts. Defaults to true.
  9. * @returns {Promise<any>} A promise that resolves with the result of the function call or rejects after all retries.
  10. */
  11. async function retry(fn, options = {}) {
  12. const { retries = 3, delay = 1000, log = true } = options;
  13. let attempts = 0;
  14. while (attempts < retries) {
  15. try {
  16. const result = await fn();
  17. if (log) {
  18. console.log(`Success after ${attempts + 1} attempts.`);
  19. }
  20. return result; // Return the result if successful
  21. } catch (error) {
  22. attempts++;
  23. if (log) {
  24. console.log(`Attempt ${attempts} failed: ${error.message}`);
  25. }
  26. if (attempts === retries) {
  27. throw error; // Re-throw the error if all retries failed
  28. }
  29. await new Promise(resolve => setTimeout(resolve, delay)); // Wait before retrying
  30. }
  31. }
  32. }

Add your comment