Retry a Promise on Failure
Retry a Promise on Failure is a reusable JavaScript snippet. Retries an async function a specified number of times when it rejects. Useful for flaky network requests. The full implementation: async function retry(fn, retries = 3, delay = 1000) { try { return await fn() } catch (error) { if (retries setTimeout(r, delay)) return retry(fn, retries - 1, delay * 2) } } // Usage const fetchWithRetry = () => retry( () => fetch('https://api.example.com/data'), 3, 1000 ) // With exponential backoff async function retryWithBackoff(fn, maxRetries = 3) { for (let i = 0; i setTimeout(r, 1000 * Math.pow(2, i))) } } } This snippet uses only standard JavaScript with no dependencies, so it runs in modern browsers and Node.js alike. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.