Last active
July 23, 2021 13:10
-
-
Save calendee/8daadf190b4c913847c52d48e45df35d to your computer and use it in GitHub Desktop.
Async Wrapper Function & JSON Fetch Handler
This file contains 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
// 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