Async Patterns
Retry, memoization (cache), and sequential processing are recurring async patterns worth knowing.
Retry, memoization (cache), and sequential processing are recurring async patterns worth knowing.
// Retry with exponential back-off
async function withRetry(fn, retries = 3, delay = 500) {
try { return await fn(); }
catch (e) {
if (retries === 0) throw e;
await new Promise(r => setTimeout(r, delay));
return withRetry(fn, retries - 1, delay * 2);
}
}
// Memoize async
const memo = new Map();
const cachedFetch = url => memo.get(url) ?? memo.set(url, fetch(url).then(r => r.json())).get(url);
Cache the Promise, not the resolved value — callers await the same Promise without duplicate fetches.
More in JavaScript