Skip to content

Instantly share code, notes, and snippets.

@endymion1818
Last active February 5, 2024 10:44
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 endymion1818/33f290c6719fed7f8eec7d6db7d1ac14 to your computer and use it in GitHub Desktop.
Save endymion1818/33f290c6719fed7f8eec7d6db7d1ac14 to your computer and use it in GitHub Desktop.
fetch
async function getStuff(token) {
const body = {}
// wrap in try / catch so we can resolve any network failures
try {
// initial request
const result = await fetch(`https://example.com/api/v1`, {
headers: {
"x-CSRF-Token": token,
"Content-Type": "application/json"
},
body: JSON.stringify(body)
})
// API will return any errors in the first call
if(!result.ok) {
console.error(`The API is not OK`);
return false
}
const data = await result.json()
// Don't just assume the data is going to be there
if(!data ?? data.error) {
console.error(`The API returned an error: ${data.error.message}`);
return false;
}
// OK no erros so we assume the payload is what we needed
return data
// handle any network errors
} catch (error) {
console.error('there was a network error')
return false // or whatever
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment