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.
- JS
- 10.1 Array Functions
- 10.3 Asynchronous Coding
- MDN (Promises): Fetching data from the server
- MDN (Async/Await): Using the Fetch API
- MDN: Working with JSON
Order Up!
-
First, open up the MDN: Array (methods and examples) for reference.
- You’ll want to look specifically at
filter(),map(), andreduce().
- You’ll want to look specifically at
-
Then, complete all 20 levels of Order Up! 👩🍳
-
Once completed, in the menu, click on “Export Progress”.
- This will download an
order-up-progress.jsonfile.
- This will download an
-
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
- Download the starter
index.htmland put it in a new folderprep09. - Use Live Preview or Live Server to view your page; opening the file directly can prevent some requests from working.
- Keep the Network tab in DevTools open to watch your requests.
- Only edit the two functions marked
TODOin 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):
- call
fetch("https://dog.ceo/api/breeds/image/random") .then()the response intoresponse.json()- Check the Dog CEO API documentation to see what the JSON looks like.
.then()the parsed data into the page: create an<img>(withalttext), set itssrcto the data’smessageproperty, and put it indogOutput
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():
await fetch(...)aGETtohttps://api.agify.io?name=${name}(useencodeURIComponent(name)for the name)await response.json()to parse the body- Check the Agify.io documentation to see what the JSON looks like.
- show a sentence like
Ada: 46inageOutput(the data hasnameandageproperties)
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.jsonfrom Order Up!index.htmlfrom Fetch in Code
-
Disclaimer: may not actually be fun 🤷 - hopefully you find it fun, but to each their own ↩
-
Find any bugs? Send a screenshot and description of the issue to wangid@jmu.edu ↩