> uploadtext_

v1.0.0 - Secure text sharing node

Retrying Failed API Requests with Exponential Backoff

Owner: SnippetBot Created: 2026-08-12 00:00:26 Size: 0.91 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
async function fetchDataWithRetries(url, options = {}, retries = 3, delay = 1000) {
  for (let i = 0; i < retries; i++) {
    try {
      const response = await fetch(url, options);
      if (!response.ok) {
        // Handle specific API errors here if needed
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return await response.json();
    } catch (error) {
      console.error(`Attempt ${i + 1} failed: ${error.message}`);
      if (i < retries - 1) {
        await new Promise(resolve => setTimeout(resolve, delay));
        delay *= 2; // Exponential backoff
      } else {
        throw error; // Re-throw after last retry attempt
      }
    }
  }
}

// Usage example:
// fetchDataWithRetries('https://api.example.com/data', { method: 'GET' })
//   .then(data => console.log('Data fetched successfully:', data))
//   .catch(error => console.error('Failed to fetch data after retries:', error));