Created
January 9, 2018 23:04
-
-
Save andon/476c3d7807c48295effa2f2bfb848517 to your computer and use it in GitHub Desktop.
Fetch with client revalidation. On failure performs another fetch without client revalidation, so that you get cached result if available.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const doFetch = (url, opts = {}) => { | |
const headers = new Headers() | |
headers.append('Cache-Control', 'max-age=0') | |
if (opts.headers) { | |
for (const header of opts.headers) { | |
headers.append(header[0], header[1]) | |
} | |
} | |
return new Promise((resolve, reject) => { | |
fetch(url, { | |
...opts, | |
headers, | |
}) | |
.then(response => { | |
if (response.ok) { | |
resolve(response) | |
} | |
throw new Error('Network response was not ok.') | |
}) | |
.catch(() => { | |
fetch(url, opts) | |
.then(resolve) | |
.catch(reject) | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment