Learn JS Async/Await,  Fetch Requests & APIs by Building a Trivia Game

Learn JS Async/Await, Fetch Requests & APIs by Building a Trivia Game

ยท

4 min read

This tutorial is available as a free Series on CodeCast!

API's are intimidating when you're learning to code, especially ones that come with really complicated docs, needs unique keys, or require authorization.

Instead of jumping headfirst into a whirlpool, we're gonna wade in slowly into the world of API's by using a free and extremely simple API from Open Trivia DB.

We're also going to go over making requests from the API using JavaScript's fetch requests while making use of await/async.

You can find the entire collection of Casts in a free Series on CodeCast. The Casts contain both the video tutorials and all the code that is written, so it's very much worth checking out!

Step One - Connect The API

In this section, we're going to connect to the API. You can watch it on the Player where you can access the code, or watch just the tutorial portion above!

Grabbing the API URL

This API is incredible simple. It doesn't require tokens or any unique identifier. You simply provide the URL and make your requests directly to the API following their conventions.

We start by creating the .js file we will be writing all our code in, which I named "app.js".

Inside, we're assigning the url we retrieved from the API to a variable. Note that the API has a 'helper' that lets you build the unique url to contain specifically what you want.

API Helper

These are the specifications I use to get the URL below:

  const url = 'https://opentdb.com/api.php?amount=100';

Now we can begin building out our fetch request. We'll start with the shell of the function:

 function getTrivia() {
 }

Inside the function, we're going to want to make a request to the url. Once we get a response from the API, we can then make use of the data that we returned:

 function getTrivia() {
   let response = fetch(url);
   let data = response.json();
   return data;
 }

However, if we were to run the function above, we would get some big problems. The code will run too quickly for the data to be retrieved by the time we're asking for it. We will not be able to be use to .json() to parse the response as it won't exist yet. This is where async/await comes in.

We will begin by placing the async keyword at the very beginning before the function declaration. This simply signifies that the function will always return a Promise. If you're not familiar with Promises, you can read up on them here.

So now our function will look like this:

 async function getTrivia() {
   let response = fetch(url);
   let data = response.json();
   return data;
 }

Now, we use the await keyword to ensure that JavaScript waits until that specific Promise is fulfilled and returns its results. We want to use it in two places within our function. Most critically, we want to use it to ensure that we don't move forward with parsing the response until the response exists. In other words, we want to add it to our fetch request.

We also want to add it to our parse request so our data is for sure parsed before it gets returned to us. Once those are done, we will return the data as normal. Our function now looks as follows:

 async function getTrivia() {
   let response = await fetch(url);
   let data = await response.json();
   return data;
 }

Now, we'll call the function to retrieve the data. But what do we do with that data? Because it's a Promise, we can use then .then() chaining method on the function to tell our application what we want to do next. In this case, we're simply going to just console.log out our data so we can ensure that our function is running smoothly. This call will look like this:

 getTrivia().then((data) => console.log(data.results));

With the result producing:

Data Results

Now that we have our API connected properly, we can begin building out the rest of the application! To find the rest of the content, you can watch them on my CodeCast Channel, by purchasing my free Series, or on YouTube (code not available for copying on YouTube).

Happy Coding ๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป

For more of my content, follow me on like Twitter & CodeCast!

ย