fetchWithRetry Promise

JavaScript
Medium

Objective

Write a function that takes a URL as a parameter, and returns a promise. The function should make an HTTP GET request to the provided URL.

  • If the request succeeds: the promise should resolve with the response data.

  • If the request fails: the function should wait for 1 second and try again. It should retry the request up to 3 times before rejecting the promise.

Requirements

  1. The function should be called fetchWithRetry

  2. It should take a single parameter which is a URL

  3. It should make a GET request to the URL

  4. If the request fails, you should retry it up to 3 times with a 1-second delay

  5. The function should return a promise

    1. If data is successfully received from the endpoint, the promise should resolve with the data

    2. If the request fails 3 times, the promise should reject with an error message

  6. You should not use any libraries (e.g. axios) to complete this task

Check your solution

Tests

Function name is fetchWithRetry
fetchWithRetry("https://www.example.com")Expected:"fetch data successfully on first try"
fetchWithRetry("http://www.example.com")Expected:"should retry and succeed on the second attempt"
fetchWithRetry("www.example.com")Expected:"should reject after 3 attempts"

Solution

Here's how I would approach this, but keep in mind there might be other ways to solve this problem.

function fetchWithRetry (url) { const maxRetries = 3; let retries = 0; // Return a promise return new Promise((resolve, reject) => { function fetchUrl () { fetch(url) .then(response => { // Check if 200 OK if (response.ok) { resolve(response); } else { // Retry retries++; if (retries >= maxRetries) { // We've reached the maximum number of retries, reject the promise reject(new Error('Maximum number of retries reached')); } else { // Try again after 1 second setTimeout(fetchUrl, 1000); } } }) .catch(reject); } fetchUrl(); }); }
Click to reveal