Last active
April 19, 2020 18:02
-
-
Save shovon/5a0fbf6527e99eb5821687a4d70a2217 to your computer and use it in GitHub Desktop.
Some async handler.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// If I don't care about the status code | |
function fetchJSON(...params) { | |
return fetch(...params).then(res => res.json()); | |
} | |
// If I do care about the status code, but don't care about the type of error. | |
async function fetchJSON(...params) { | |
const res = await fetch(...params); | |
if (res.status >= 400) { | |
throw new Error(res.statusText); | |
} | |
return res.json(); | |
} | |
// If I care about any errors. | |
async function fetchJSON(...params) { | |
const res = await fetch(...params); | |
if (res.status >= 400) { | |
return { | |
error: { status: res.status, statusText: res.statusText }; | |
} | |
} | |
return { data: res.json() }; | |
} | |
// In the last example, I'd use the function like this (assuming I'm in an async function): | |
const { data, error } = await fetchJSON(...params); | |
if (error) { | |
// Do stuff here. | |
} | |
// Do stuff with data here. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment