fetch-retry in about 88 lines of code provides an extension to the fetch API to accept retries, retryDelay, and retryOn on the options object, when omitted will default to 3 retries, a 1000ms retry delay, and to retry only on network errors.
Get it:npm install fetch-retry
Smaple usages:
1
constfetch=require('fetch-retry');
1234567891011
fetch(url,{retries:3,retryDelay:1000}).then(function(response){returnresponse.json();}).then(function(json){// do something with the resultconsole.log(json);});
1234567891011
// Retry on 503fetch(url,{retryOn:[503]}).then(function(response){returnresponse.json();}).then(function(json){// do something with the resultconsole.log(json);});
12345678910111213141516
// Custorm retryfetch(url,{retryOn:function(attempt,error,response){// retry on any network error, or 4xx or 5xx status codesif(error!==null||response.status>=400){console.log(`retrying,attemptnumber${attempt+1}`);returntrue;}}).then(function(response){returnresponse.json();}).then(function(json){// do something with the resultconsole.log(json);});}