Skip to content

Instantly share code, notes, and snippets.

@shovon
Last active April 19, 2020 18:02
Show Gist options
  • Save shovon/5a0fbf6527e99eb5821687a4d70a2217 to your computer and use it in GitHub Desktop.
Save shovon/5a0fbf6527e99eb5821687a4d70a2217 to your computer and use it in GitHub Desktop.
Some async handler.
// 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