Backoff Decorator For Async Methods

Apply exponential backoff retry to async methods via a decorator with per-method configuration and error filtering.

JavascriptResilience

Code

javascriptsnippet
1 line
export function withBackoff({maxAttempts=3,baseDelay=100,shouldRetry=()=>true}={}){return function(target,propertyKey,descriptor){const original=descriptor.value;descriptor.value=async function(...args){let attempt=0,lastErr;while(attempt<maxAttempts){try{return await original.apply(this,args);}catch(e){lastErr=e;attempt++;if(attempt>=maxAttempts||!shouldRetry(e))break;await new Promise(r=>setTimeout(r,baseDelay*2**attempt));}}throw lastErr;};return descriptor;};}

How it works

Everything happens inside the function withBackoff.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Using it in your own code

Entry signature: export function withBackoff({maxAttempts=3,baseDelay=100,shouldRetry=()

The surface worth importing is withBackoff; the helpers around it are private to the snippet.

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. The file defines `withBackoff` at load time.