Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jkantr/62d43e8226d97f03c309736ebcf298f0 to your computer and use it in GitHub Desktop.
Save jkantr/62d43e8226d97f03c309736ebcf298f0 to your computer and use it in GitHub Desktop.
const checkStatus = (response) => {
if (response.status >= 200 && response.status < 300) return response
const error = new Error(`Error ${response.status}: ${response.statusText}`)
error.response = response
throw error
}
const parseResponse = (response) => {
const authToken = response.headers.get(`Authorization`)
return response.json().then(json => ({ authToken, json }))
}
const getAuthTokenAndJSON = () => {
return fetch(url, {opts})
.then(checkStatus)
.then(parseResponse)
}
// and call thusly:
getAuthTokenAndJSON()
.then({ authToken, json } => {
// now you have both the authToken and json
}
.catch(err => console.warn(err.message)) // now the error contains the whole response object too if you need it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment