Skip to content

Instantly share code, notes, and snippets.

@methbkts
Created November 5, 2019 16:15
Show Gist options
  • Select an option

  • Save methbkts/fc42a17d6ffb8a23aa53bbd0ea952177 to your computer and use it in GitHub Desktop.

Select an option

Save methbkts/fc42a17d6ffb8a23aa53bbd0ea952177 to your computer and use it in GitHub Desktop.
Sample to Fetch API
fetch('some-url')
.then(handleResponse)
.then(data => console.log(data))
.catch(error => console.log(error))
function handleResponse (response) {
let contentType = response.headers.get('content-type')
if (contentType.includes('application/json')) {
return handleJSONResponse(response)
} else if (contentType.includes('text/html')) {
return handleTextResponse(response)
} else {
// Other response types as necessary.
throw new Error(`Sorry, content-type ${contentType} not supported`)
}
}
function handleJSONResponse (response) {
return response.json()
.then(json => {
if (response.ok) {
return json
} else {
return Promise.reject(Object.assign({}, json, {
status: response.status,
statusText: response.statusText
}))
}
})
}
function handleTextResponse (response) {
return response.text()
.then(text => {
if (response.ok) {
return json
} else {
return Promise.reject({
status: response.status,
statusText: response.statusText,
err: text
})
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment