/**
* Retries a function call with customizable retry options.
*
* @param {Function} fn The function to retry.
* @param {object} options Optional retry configuration.
* @param {number} options.retries The maximum number of retries. Defaults to 3.
* @param {number} options.delay The delay between retries in milliseconds. Defaults to 1000.
* @param {boolean} options.log The flag to log the retry attempts. Defaults to true.
* @returns {Promise<any>} A promise that resolves with the result of the function call or rejects after all retries.
*/
async function retry(fn, options = {}) {
const { retries = 3, delay = 1000, log = true } = options;
let attempts = 0;
while (attempts < retries) {
try {
const result = await fn();
if (log) {
console.log(`Success after ${attempts + 1} attempts.`);
}
return result; // Return the result if successful
} catch (error) {
attempts++;
if (log) {
console.log(`Attempt ${attempts} failed: ${error.message}`);
}
if (attempts === retries) {
throw error; // Re-throw the error if all retries failed
}
await new Promise(resolve => setTimeout(resolve, delay)); // Wait before retrying
}
}
}
Add your comment