Skip to content

Instantly share code, notes, and snippets.

@adamjohnson
Last active December 21, 2021 18:33
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 adamjohnson/4ff2b0dc3f59fffbc03bf970a2912158 to your computer and use it in GitHub Desktop.
Save adamjohnson/4ff2b0dc3f59fffbc03bf970a2912158 to your computer and use it in GitHub Desktop.
Reusable JavaScript fetch functions for JSON GET requests
/*
Reusable `fetch` functions for JSON GET requests
Examples in ES8 & ES5+ for older browser support
*/
'use strict';
const endpoint = 'https://api.chucknorris.io/jokes/random';
// The reusable ES2017 (ES8) function (GET requests & JSON only):
const fetchData = async (apiUrl) => {
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`❌ Network response was not OK: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error(`There has been a problem with your fetch operation: ${error}`);
}
};
// =====================
// OR, if you need to support older browsers:
// NOTE: IE11 requires a `fetch`` polyfill, supports `const`/`let`
const fetchDataES5 = function (apiUrl) {
fetch(apiUrl)
.then(function (response) {
if (!response.ok) {
throw new Error('❌ Network response was not OK: ' + response.status);
}
return response.json();
})
.then(function (data) {
console.log(data.value); // NOTE: remove `.value` if you don't use the Chuck Norris API.
})
.catch(function (error) {
console.error('There has been a problem with your fetch operation: ', error);
});
};
const es5Function = function () {
fetchDataES5(endpoint);
}
es5Function();
// =====================
// Method 1, standard ES6 async function:
const methodOne = async () => {
const theData = await fetchData(endpoint); // Must be used in an async function (sans top-level await).
console.log(theData.value); // NOTE: remove `.value` if you don't use the Chuck Norris API.
};
methodOne();
// =====================
// Method 2, ES6 IIFE:
(async () => {
const theData = await fetchData(endpoint); // Must be used in an async function (sans top-level await).
console.log(theData.value); // NOTE: remove `.value` if you don't use the Chuck Norris API.
})();
// =====================
/* Method 3, Top Level Await:
NOTE: If you want to use top-level await,
you must use ES Modules OR have the file extension: `.mjs`:
https://flaviocopes.com/javascript-await-top-level/
Be careful with browser support (Safari!).
*/
const theData = await fetchData(endpoint);
console.log(theData.value);
// 👇 Looking for a resusable aysnc `fetch()` function that accepts POST requests?
// https://gist.github.com/wayanjimmy/45a1ad40f3ae7bb8a2b6716a44093eb1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment