0

How do I retry this fetch x times if it fails?

The code is based on this article: https://dmitripavlutin.com/javascript-fetch-async-await/

async function fetchData() {
  const [firstResponse, secondResponse] = await Promise.all([
    fetch(firstUrl),
    fetch(secondUrl),
  ]);

  const first = await firstResponse.json();
  const second = await secondResponse.json();

  return [first, second];
}

fetchData()
  .then(([first, second]) => {
    console.log("success");
  })

  .catch((error) => {
    console.log("error");
  });

Lars Bing
  • 11
  • 2

1 Answers1

0

Since the requests are independent of each other, I'd have a utility function that will retry X times and then use that in the Promise.all. I'd also have a utility function for fetching JSON that handles the fetch API footgun where it doesn't check HTTP success (see my blog post here). So something along these lines:

// Fetch JSON
function fetchJSON(...args) {
    const response = await fetch(...args);
    if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
    }
    return response.json();
}

// Fetch JSON with up to `retries` retries
async fetchJSONWithRetry(retries, ...args) {
    while (retries > 0) {
        try {
            const result = await fetchJSON(...args);
            return result;
        } catch (e) {
            if (--retries === 0) {
                throw e;
            }
        }
    }
}

// Your `fetchData`
async function fetchData(retries = 5) {
    const [first, second] = await Promise.all([
        fetchJSONWithRetry(retries, firstUrl),
        fetchJSONWithRetry(retries, secondUrl),
    ]);
  
    return [first, second];
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875