Skip to content

Instantly share code, notes, and snippets.

@calendee
Last active July 23, 2021 13:10
Show Gist options
  • Save calendee/8daadf190b4c913847c52d48e45df35d to your computer and use it in GitHub Desktop.
Save calendee/8daadf190b4c913847c52d48e45df35d to your computer and use it in GitHub Desktop.
Async Wrapper Function & JSON Fetch Handler
// Based on https://www.maxpou.fr/async-await-without-try-catch and https://github.com/DavidWells/safe-await/pull/2/files
export function wrapAsyncFn<T>(somePromise: Promise<T>) {
return somePromise.then((data) => [null, data]).catch((err) => [err, null]);
}
// Based on https://www.youtube.com/watch?v=aIboXjxo-w8
export async function fetchJson(
input: RequestInfo,
init?: RequestInit | undefined,
) {
const [error, response] = await wrapAsyncFn(fetch(input, init));
if (error) {
return [undefined, "Server error"];
}
const contentType = response?.headers?.get("content-type");
if (!response.ok || !contentType.includes("application/json")) {
return [undefined, "Server error"];
}
const json = await response.json();
return [json, undefined];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment