Implement retryBackoff(fn, options)
Real production code: any call to a flaky network dependency needs this, and it's a genuinely common senior-level async question because it combines promises, timing, and error handling in one place.
Write retryBackoff(fn, options) where fn is an async function and options is { retries, baseDelay }:
- Calls
fn(). If it succeeds, resolve with its result immediately. - If it throws, wait
baseDelay * 2^attemptmilliseconds, then try again, up toretriesadditional attempts. - If every attempt fails, reject with the last error.
await retryBackoff(flakyApiCall, { retries: 3, baseDelay: 100 });
// attempt 1 fails → wait 100ms → attempt 2 fails → wait 200ms → attempt 3 succeeds