/* 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/ */ 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