Skip to content

Instantly share code, notes, and snippets.

@tyte
Created April 25, 2022 06:42
Show Gist options
  • Save tyte/7b2049aaccf1d6fd7db5c87f1c68e45a to your computer and use it in GitHub Desktop.
Save tyte/7b2049aaccf1d6fd7db5c87f1c68e45a to your computer and use it in GitHub Desktop.
JS fetch api data with async await
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Random Ron</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
body {
margin: 0 auto;
max-width: 40em;
width: 88%;
}
</style>
</head>
<body>
<h1>Random Ron</h1>
<blockquote id="quote" aria-live="polite">
<em>Quotes are on their way...</em>
</blockquote>
<p>
<button id="get-quote">More Ron</button>
</p>
<script>
// Your code goes here...
let button = document.querySelector('#get-quote');
let quote = document.querySelector('#quote');
let api = 'https://ron-swanson-quotes.herokuapp.com/v2/quotes';
// create an empty array that will store quotes
let quotes = [];
/*
async function displayQuote() {
// 1. Fetch - if response is ok, then return json, otherwise throw error
// 2. Then chain .then to do stuff with data
// 3. Then chain .catch for errors
await fetch(api).then(function (response) {
if (response.ok) {
return response.json();
}
throw response.status;
}).then(function (data) {
// NEW: remove first quote if there are at least 50 quotes
if (quotes.length > 49) {
quotes.shift();
};
if (quotes.includes(data[0])) {
// console.log('SAME COPY!');
// console.log(data[0]);
displayQuote();
// NEW: add return!
return;
} else {
quote.textContent = data[0];
quotes.push(data[0]);
// console.log(quotes);
}
}).catch(function (error) {
quote.textContent = 'Error message, a very beautiful one.'
});
}
displayQuote();
*/
// Async ALWAYS returns a promise, even if you are not asynchronious code.
async function displayAsyncQuote() {
try {
let response = await fetch(api);
if (!response.ok) {
throw response.status;
}
let data = await response.json();
if (quotes.length > 49) {
quotes.shift();
};
if (quotes.includes(data[0])) {
// console.log('SAME COPY!');
// console.log(data[0]);
displayQuote();
// NEW: add return!
return;
} else {
quote.textContent = data[0];
quotes.push(data[0]);
// console.log(quotes);
}
} catch (error) {
console.warn(error);
quote.textContent = 'Error message, a very beautiful one.'
}
}
displayAsyncQuote();
button.addEventListener('click', displayAsyncQuote);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment