JSON and Promises

In this lab, you will use fetch and Promises to retrieve a web-based data set that is processed asynchronously.


You will need to consult the Bootstrap and JavaScript documentation throughout this lab.


Starting Code

Start by downloading and extracting the source code in this ZIP file:

There are two source code files: index.html and data.js. You will need to modify both files.

This lab is using JSON data provided by The World Bank. You do not need to study this API, but it is provided here as reference.


Step 1: Asynchronous function calls

Your first step is to complete the addValidCountries() function. Use a call to fetch and parse a JSON data set with a collection of country names. Use the await keyword here to make sure that you get the results as an array. Once you have the data, loop through it to create new data list options as described in the comments.


Step 2: Creating a Promise

Your next step is to complete the validateQuery() and fetchCountry() functions to submit a query to the the World Bank. It is strongly recommended that you view one of the data sets here. This shows you the structure of the data sets that we will be working with.

In validateQuery(), you will call validateForm(), which returns four values as an array. The first indicates whether or not the form data is valid. If so, pass the other three (as an array) to the resolve() function in the Promise. Otherwise, send an error message to reject().

In fetchCountry(), you will create a query URL using the global variables described and the criteria parameter. This URL should be passed to fetch() with the result being passed to resolve().


Step 3: Linking the Promises

Finally, you will complete the processData() function and the self-executing initialization function. The latter function will call addValidCountries() to udpate the datalist element in the form. You'll then add a submit event listener to the form to do the following steps:

  1. Call preventDefault() and stopPropagation() on the event to make sure the page doesn't reload.
  2. Create a sequence of .then() and .catch() calls to chain the helper functions (validateQuery, fetchCountry, response.json, processData, and displayError) together.

Submission

When you are finished, upload just your data.js file to Canvas.



James Madison University logo


© 2011-2024 Michael S. Kirkpatrick.
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.