UNPKG

@bernierllc/retry-policy

Version:

Atomic retry policy utilities with exponential backoff and jitter

54 lines (45 loc) 1.67 kB
/* Copyright (c) 2025 Bernier LLC This file is licensed to the client under a limited-use license. The client may use and modify this code *only within the scope of the project it was delivered for*. Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC. */ import { RetryPolicy, createRetryPolicy } from '../src'; /** * Basic usage example for @bernierllc/retry-policy */ async function basicUsageExample() { // Create a retry policy with default settings const policy = new RetryPolicy({ maxRetries: 3, initialDelayMs: 1000, shouldRetry: (error) => error.code === 'NETWORK_ERROR' }); // Simulate an operation that might fail async function unreliableOperation() { const random = Math.random(); if (random < 0.7) { throw new Error('Network error'); } return 'Success!'; } // Use the retry policy in a retry loop for (let attempt = 0; attempt <= 3; attempt++) { try { const result = await unreliableOperation(); console.log('Operation succeeded:', result); break; // Success, exit retry loop } catch (error) { const retryResult = policy.evaluateRetry(attempt, error); if (!retryResult.shouldRetry) { console.log('All retry attempts exhausted'); throw error; // Don't retry, re-throw error } console.log(`Attempt ${attempt + 1} failed, retrying in ${retryResult.delay}ms...`); // Wait before next attempt await new Promise(resolve => setTimeout(resolve, retryResult.delay)); } } } // Run the example basicUsageExample().catch(console.error);