Skip to content

Prep 9: Array Functions, Asynchronicity, and Data Processing

Textbook Reading

Don’t forget! We recommend starting with the activity and then using the textbook reading to help you understand the concepts and complete the activity.

Order Up!

  1. First, open up the MDN: Array (methods and examples) for reference.

    • You’ll want to look specifically at filter(), map(), and reduce().
  2. Then, complete all 20 levels of Order Up! 👩‍🍳

    • This is a fun1 game made in-house by Dr. Wang2 to help you learn and practice these fundamental higher-order array methods.
  3. Once completed, in the menu, click on “Export Progress”.

    • This will download an order-up-progress.json file.
  4. Keep this file for submission (see bottom of page).

Fetch in Code

In Prep 7, you sent requests by hand with Hoppscotch. Now you’ll make the same kinds of requests from JavaScript using fetch(), first with promises and then with async/await.

Getting Started

  1. Download the starter index.html and put it in a new folder prep09.
  2. Use Live Preview or Live Server to view your page; opening the file directly can prevent some requests from working.
  3. Keep the Network tab in DevTools open to watch your requests.
  4. Only edit the two functions marked TODO in the <script>; the rest is provided.

Part 1: Promises with .then()

Use the MDN guide Fetching data from the server to help you.

Fill in showRandomDog() using a promise chain (no async/await):

  1. call fetch("https://dog.ceo/api/breeds/image/random")
  2. .then() the response into response.json()
  3. .then() the parsed data into the page: create an <img> (with alt text), set its src to the data’s message property, and put it in dogOutput

Each click of “New dog” should replace the previous picture.

Hint

Follow the example fetch in The Fetch API section of the guide. Copy its example (after “Finally we’re ready to use the Fetch API:”) into showRandomDog() and change the URL and what happens in the .then() callbacks to match the steps above.

Solution

Try the hint first! Open this only once you’re really stuck.

Are you sure?
function showRandomDog() {
  fetch("https://dog.ceo/api/breeds/image/random")
    .then((response) => response.json())
    .then((data) => {
      const img = document.createElement("img");
      img.src = data.message;
      img.alt = "A random dog";
      dogOutput.replaceChildren(img);
    });
}

Part 2: async/await

Use the MDN guide Using the Fetch API to help you.

Fill in guessAge(name) using async/await instead of .then():

  1. await fetch(...) a GET to https://api.agify.io?name=${name} (use encodeURIComponent(name) for the name)
  2. await response.json() to parse the body
  3. show a sentence like Ada: 46 in ageOutput (the data has name and age properties)

The form is already hooked up, so try other names.

Hint

The basic structure of an async function looks like this:

async function myFunction() {
  const response = await fetch(url);
  const data = await response.json();
  // use data here
}

The async keyword goes before function, and each await pauses until that promise is ready, so you can use the result on the next line. Compare it with Part 1: each .then() becomes a line with await.

Solution

Try the hint first! Open this only once you’re really stuck.

Are you sure?
async function guessAge(name) {
  const response = await fetch(`https://api.agify.io?name=${encodeURIComponent(name)}`);
  const data = await response.json();
  ageOutput.textContent = `${data.name}: ${data.age}`;
}

Submission

Upload the following to the corresponding Gradescope assignments:

  • order-up-progress.json from Order Up!
  • index.html from Fetch in Code

  1. Disclaimer: may not actually be fun 🤷 - hopefully you find it fun, but to each their own ↩

  2. Find any bugs? Send a screenshot and description of the issue to wangid@jmu.edu ↩