Skip to content

Instantly share code, notes, and snippets.

@karlhorky
Created January 26, 2019 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karlhorky/30ceb7ba6756690e253a22720f5f5604 to your computer and use it in GitHub Desktop.
Save karlhorky/30ceb7ba6756690e253a22720f5f5604 to your computer and use it in GitHub Desktop.
Fetch with Timeout
// Fetch with timeout
// Source: https://github.com/whatwg/fetch/issues/179#issuecomment-457698748
const networkTimeoutError = new Error('Network request timeout')
function getTimeout({ timeout }) {
if (timeout && timeout.constructor === Promise) {
return timeout
}
if (typeof timeout === 'number') {
return new Promise(resolve => {
setTimeout(resolve, timeout)
})
}
}
export default function fetchWithTimeout(url, config) {
return new Promise((resolve, reject) => {
let completed = false
const timeout = getTimeout(config)
const wrap = (thing, ...pre) => (...args) => {
if (!completed) {
completed = true
return thing(...pre, ...args)
}
}
delete config.timeout
if (timeout) {
timeout.then(wrap(reject, networkTimeoutError))
}
return fetch(url, config)
.then(wrap(resolve))
.catch(wrap(reject))
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment