Skip to content

Instantly share code, notes, and snippets.

@geckofu
Last active August 25, 2017 11:52
Show Gist options
  • Save geckofu/7ae45872396d47cd7542cb0596f11177 to your computer and use it in GitHub Desktop.
Save geckofu/7ae45872396d47cd7542cb0596f11177 to your computer and use it in GitHub Desktop.
Explicit error handling, timeoutable `fetch()`
// 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