UNPKG

@mebsly/retry

Version:

A flexible and configurable retry mechanism for JavaScript functions and fetch requests with exponential delay

2 lines (1 loc) 705 B
function retry(f,o={}){const c=retry.config||{},r=o.retries??c.retries??3,d=o.delay??c.delay??500,s=o.shouldRetry??c.shouldRetry??(()=>true),m=o.maxDelay??c.maxDelay??1e4;return new Promise((a,b)=>{let t=0;function e(){Promise.resolve().then(f).then(a).catch(e=>{t++;t>r||!s(e)?b(e):setTimeout(e,Math.min(d*Math.pow(2,t-1),m))})}e()})}retry.config={retries:3,delay:500,maxDelay:1e4,shouldRetry:e=>true};retry.fetch=(u,f={},o={})=>retry(()=>fetch(u,f).then(r=>{if(!r.ok)throw new Error(`HTTP error ${r.status}`);return r.json()}),{...o,shouldRetry:o.shouldRetry??(e=>e instanceof Error&&e.message.includes('HTTP error')?(t=parseInt(e.message.split(' ')[2]),t>=500||t===429):true)});module.exports=retry;