Intro to Network Requests

By the end of this lesson you should…

  • Understand the difference between synchronous and asynchronous operations
  • Be familiar with the fetch API
  • Understand how network requests work
  • Know what a GET request does and how to use it


  • Async / Asynchronous Executing code without blocking the execution of code after it
  • AJAX Updating a webpage based on data from the network without reloading the whole thing

What is this asynchronous thing all about?

Let’s say we’re at a Red Robin for a night out on the town…Here’s how the experience would go in each scenario:

  • Synchronous: I order my food, everyone in the restaurant has to wait until I get my food before the next person can order

  • Asynchronous: Like, a normal restaurant experience where you’d tip the server at least 20%

Example: setTimeout()


setTimeout(() => {
}, 2000);

console.log("Wait for it...");

setTimeout is actually an asynchronous function, which executes its callback after waiting for the allotted time to expire.

Example 2:

  • Synchronous:
  • Asynchronous:


  • Why are async operations necessary?
  • Have you run into a situation on past projects where you needed async operations to accomplish it?

The history of network requests

What is a network request?

Open up your dev tools and navigate to the Network tab. Refresh the page and watch what happens.

network dev tool example

Each item on a webpage is coming from some server somewhere. The link tags in your HTML connecting your stylesheets and JavaScript files prompt network requests. Webpack saves us time because it bundles up all our files into a single JavaScript file, necessitating a single network request, rather than dozens of individual requests.

Why is it important to keep this in mind?

Each network request takes time - they’re expensive. Imagine if you had to wait for a webpage to load one thing at a time! It would not make for a great user experience.

Network requests are expensive no matter what we do. However, we can run them asynchronously, saving some time.

The first development: AJAX

Asynchronous JavaScript And XML

Cool, but really, what is it?

“the method of exchanging data with a server, and updating parts of a web page – without reloading the entire page.”

The two main benefits of AJAX are:
  1. Make requests to the server without reloading the entire page
  2. Receive and work with data from the server


  1. An event occurs in a web page (the page is loaded, a button is clicked)
  2. An XMLHttpRequest object is created by JavaScript
  3. The XMLHttpRequest object sends a request to a web server
  4. The server processes the request
  5. The server sends a response back to the web page
  6. The response is read by JavaScript
  7. Proper action (like page update) is performed by JavaScript

Using the XMLHttpRequest object, developers can GET information to/from remote servers (among other tasks you’ll learn more about in future mods). Depending on how the information is transmitted, the server should respond back with a status code. Here is a high-level summary of the status code ranges:

the XHR or XMLHttpRequest is a tool specific to the browser

1XX status codes have informational purposes
2XX indicates success
3XX is for redirection
4XX represent client-side errors
5XX indicate problems on the server side
  • 200 - OK
    • Typically the response you’re hoping for when trying to get information from an API
  • 400 - Bad Request
    • The server did not comprehend the request
  • 404 - Not Found
    • The server did not match any of the parameters you requested
  • 500 - Internal Server Error
    • It’s the server’s fault

google 500 error

Practice Time!

Open up your console and walk through these steps:

First create a new instance of an XMLHttpRequest Object:

var xhttp = new XMLHttpRequest();

Next let’s initialize the request using the open() method.

We will hit this trivia API. We’ll need to use the GET method, define our endpoint, and provide a 3rd argument of TRUE which tells the request to be asynchronous:"GET", "", true);

Now let’s send the request:


If it worked, you should be able to type xhttp and see the results in your XMLHttpRequest object with a status of 200 as well as some responseText containing the specific trivia returned.

Isn’t There an Easier Way???

Like basically all things in Javascript, developers have come up with synctatic sugar to make our lives easier.

jQuery: $.get()

jQuery has incorporated AJAX functionality into its library to allow us to perform asynchronous tasks in a more readable fashion. Here is a sample request matching what we did above:


Of course there is more to it in order to use the data returned by the server, but this is all it takes to ping those endpoints and request the data.

If we want to do something with the data, we can set a callback as a second argument that handles the data returned:

$.get("", (data) => {
  //do something with the data

But what about if we request something that doesn’t exist or the server is busted, how can we account for that? Great question! Because jQuery returns a jqXHR (or just an XMLHttpRequest object), we get with it a variety of tools for how to deal with the response. Here’s one example:

  .then(data => //do something if data is returned)
  .catch(error => //do something if an error is returned)

Some additional information on the specifc methods can be found here

ES6: fetch()

Another great tool to help with network requests is the fetch API. This is what we’ll focus on in Mod 2, since we can use it “for free” with ES6 (as opposed to $.get which requires us to bring in jQuery)!

It’s important to note that not every browser supports the fetch api; polyfills are available, but many legacy codebases use other apis that are supported by older browsers, such as Axios or Superagent.

From the docs:

The fetch() method takes one mandatory argument, the path to the resource you want to fetch. It returns a promise that resolves to the Response to that request, whether it is successful or not.

We can nearly mimic the syntax above to perform the same network request, with a few minor tweaks. First we need to pass in the path we want to fetch from:


Next we see that fetch returns a promise that resolves to the response of of our request. We haven’t talked about promises yet, but all you need to know for now is that we can add .then(callback) to our fetch. The callback parameter inside the .then() method will execute as soon as the response comes in. In other words, it will wait until we have ALL of the data (or an error) back, THEN it will execute whatever we say to do next with that data.

  .then(data => console.log(data))

If you plug the code above into your console, you should see the Response object come back!

However, there’s one problem: we can’t seem to get the data we want from the Response.body. There’s one more step to parse the data (much like you do when pulling things from localStorage). We’ll need to use the Body.json() method that comes with fetch to parse it and call another .then(). (See code snippet below)

From the docs, the .json() method returns “A promise that resolves with the result of parsing the body text as JSON. This could be anything that can be represented by JSON — an object, an array, a string, a number…”

In short, it gives us access to the data!

  .then(data => data.json())
  .then(data => console.log(data))

Lastly, we can add in a .catch() to account for any errors we may run into.

  .then(data => data.json())
  .then(data => console.log(data))
  .catch(err => /* do something else */)


“A Promise is an object representing the eventual completion or failure of an asynchronous operation”

In our case, we can think of Promises as a placeholder that will do something once it receives a response back from the trivia server.

The great thing about promises is that since they are just objects we can move them around like an object and can return them from functions.

function getTrivia(number, categoryId) {
	const root = '';
	const url = `${root}?amount=${number}&category=${categoryId}&type=multiple`;
	const promise = fetch(url)
	                .then(data => data.json());
	return promise;

getTrivia(10, 27)
.then(data => console.log(data))
.catch(err => /* do something else */);

Practice Time!

In your console do the following…

  • Fetch 10 science questions using fetch and console.log the entire response
  • Fetch 20 geography questions and for each trivia console.log the answer only
  • Fetch 20 geography questions and console.log the response status code.
  • Fetch 30 geography questions and console.log an array of only the hard trivia

Even more practice time:

This repo has instructions in the README for implementing a fetch request into a basic React app.

Try it out!

Further Reading:

Lesson Search Results

Showing top 10 results