Skip to content

Instantly share code, notes, and snippets.

@developit
Created May 8, 2019 22:39
Show Gist options
  • Select an option

  • Save developit/a4861ad63081677b7c2945cd39cca8c0 to your computer and use it in GitHub Desktop.

Select an option

Save developit/a4861ad63081677b7c2945cd39cca8c0 to your computer and use it in GitHub Desktop.

Revisions

  1. developit created this gist May 8, 2019.
    28 changes: 28 additions & 0 deletions fetch-with-retry.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    // import fetch from 'isomorphic-unfetch';

    const RETRIES = 5;

    /**
    * Example:
    * global.fetch = fetchWithRetry;
    */

    function fetchWithRetry(url, options) {
    const opts = options || {};
    // only retry if the request is GET or HEAD:
    if (/(get|head)/i.test(opts.method)) {
    return doFetch(url, opts, opts.retries || RETRIES);
    }
    return fetch(url, opts);
    }

    function doFetch(url, options, retriesRemaining) {
    return fetch(url, options).catch(err => {
    if (err.timedout) { // you have to figure out when you want to retry
    if (retriesRemaining) {
    return doFetch(url, options, retriesRemaining - 1);
    }
    }
    throw err;
    });
    }