Create a function fetchDataWithRetry(url, maxAttempts, delay)
that tries to fetch data from the given URL using the provided fetchData(url)
function. It retries up to maxAttempts
times if the request fails and uses exponential backoff (doubles the delay after each failure).
If all attempts fail, it rejects with an error message: Failed to fetch data from <url> after <maxAttempts> attempts.
The fetchData
function simulates an API with a 30% failure rate using Math.random() > 0.3
. This generates a random number between 0 and 1, resolving the promise when the value is above 0.3 (70% of cases) and rejecting it otherwise (30% of cases).
For example: