Last active
August 25, 2017 11:52
-
-
Save geckofu/7ae45872396d47cd7542cb0596f11177 to your computer and use it in GitHub Desktop.
Explicit error handling, timeoutable `fetch()`
This file contains hidden or 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
// Inspired by davej's gist: https://gist.github.com/davej/728b20518632d97eef1e5a13bf0d05c7 | |
// Accepts same arguments as `fetch()`, then returns a promise | |
// - Reject if response is not ok (4xx, 5xx) | |
// - Reject if timeout (by default, a fetch won't timeout) | |
const enhancedFetch = (...args) => { | |
const whinyFetch = fetch(...args) | |
.then((response) => { | |
if (response.ok) { | |
return response | |
} | |
throw new Error('Response was not ok') | |
}) | |
return Promise.race([ | |
whinyFetch, | |
new Promise((_, reject) => { | |
setTimeout(() => reject(new Error('Fetch Timeout')), 7000) | |
}) | |
]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment