Retry an async function with exponential backoff to handle transient failures gracefully.
Code
Boilerplatesconst retry = async (fn, retries = 3, delay = 10) => {
try {
return await fn();
} catch (e) {
if (retries === 0) throw e;
await new Promise(r => setTimeout(r, delay));
return retry(fn, retries - 1, delay * 2);
}
};
let attempts = 0;
const result = await retry(async () => {
attempts++;
if (attempts < 3) throw new Error('fail');
return 'success';
});
return `${result} after ${attempts} attempts`;Browser·fetch() may be limited by CORS
More JavaScript Snippets
Debounce
Create a debounced function that delays execution until after a specified wait period has elapsed since the last call.
Memoize
Cache function results to avoid redundant calculations and improve performance for expensive operations.
Once
Create a function that can only be called once, returning the cached result for subsequent invocations.
Parallel with Limit
Run promises in parallel with a concurrency limit to control resource usage and prevent overwhelming external services.
Promise.allSettled
Wait for all promises to settle, whether they resolve or reject.
Promise.any
Return the result of the first promise that resolves successfully.