Async & Promisesmedium
Implement retry(fn, retries, delay) with backoff
Implement a Promise-based retry utility for flaky APIs. Retry failed async calls with exponential backoff and stop after max retries.
Asked at Amazon, Netflix, Google
Answer
function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)) } async function retry(fn, retries = 3, baseDelay = 100) { let attempt = 0 let lastError while (attempt <= retries) { try { return await fn() } catch (err) { lastError = err if (attempt === retries) break const wait = baseDelay * 2 ** attempt // exponential backoff await sleep(wait) attempt++ } } throw lastError } // Usage let calls = 0 retry(async () => { calls++ if (calls < 3) throw new Error('temporary') return 'success' }, 4, 50).then(console.log)