Codepath

Asynchronous JavaScript

Introducing the Fetch API

Now that we know how to build our request following HTTP Protocol, it's time to learn how to send the request.

The fetch method from the Fetch API takes in one argument, the path, and returns a Response. The syntax is simple, here's an example of fetch call:

const response = fetch('http://example.com/movies.json')

Data returned from an API are typically either XML (eXtensible Markup Language) or JSON (JavaScript Object Notation).

XML is similar to HTML without predefined tags. Most tags are custom to the type of data it includes.

<gif>
  <type>gif</type>
  <id>YsTs5ltWtEhnq</id>
  <slug>confused-flying-YsTs5ltWtEhnq</slug>
  <url>http://giphy.com/gifs/confused-flying-YsTs5ltWtEhnq</url>
  <username>JoeCool4000</username>
</gif>

JSON is similar to JavaScript objects, using notation similar to a key/value pair.

"gif": {
 "type": "gif",
 "id": "YsTs5ltWtEhnq",
 "slug": "confused-flying-YsTs5ltWtEhnq",
 "url": "http://giphy.com/gifs/confused-flying-YsTs5ltWtEhnq",
 "username": "JoeCool4000"
}

Both types of formats are widely used but JSON is more commonly used by developers. JSON is typically easier to parse and works better with JavaScript.

Since the fetch method returns a Response object, we need to take an extra measure to turn the response to a JSON data type and then extract the data.

  1. On the Response object, we use the .json() method to convert the Response object to a JSON body text.
  2. On the JSON object, we use the data attribute to extract the data.
const response = fetch('http://example.com/movies.json')
const jsonResponse = response.json();
const data = jsonResponse.data;

You may notice that when attempting to run the fetch method we provided above you will get an error in the console. This is because all of these actions execute sequentially. We don't want to launch the next action until we know that we have successfully received the data from our first action. This is called asynchronous programming. In JavaScript we will use the keywords async and await to define an asynchronous function and await to indicate when actions should wait on the return of a promise from the previous action. We will explain this further in the next steps!

What is Asynchronous JavaScript?

Sometimes you have functions in your code that rely on information or data from another step in your program flow. You see this quite often when you are loading a web page on a browser and you see the spinning wheel :loading:.

You don't want your users to only see a blank screen, instead, there may be other things your server can do to load other parts of your webpage while they wait for results. This is exactly the basis of asynchronous programming. Asynchronous programming relies heavily on the blocking of code to separate functions that are dependent or independent.

The fetch() method is a perfect example of an asynchronous function. In order to parse through results and use the json attribute, we need to ensure that fetch was able to return a response.

Traditionally, programmers use chaining of methods by attaching a then() method to highlight the asynchronous nature parsing through response data. You may see older tutorials using the fetch() method follow the syntax below:

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

By chaining of functions, this ensures that the .json attribute isn't called unless the fetch returns a response and so on.

Introducing Promises

A promise is a modern version of an XMLHttpRequest. This was introduced with the fetch() method and allows the computer to easily handle a request regardless of the state of the response. This means that valid requests were handled equally as fast as invalid or failed requests.

The async and await syntax was introduced with the ECMAScript 2017 update. These keywords are used to indicate asynchronous functions or code.

  • async is used to indicate an asynchronous function and appears before the function definition.
//async function
async function hello() { return "Hello" };

//async function expression
let hello = async function() { return "Hello" };
  • await is best used in combination with async function definitions. It is used with any Promise-based function to pause code or with a function that returns a Promise. Most specifically, with web API functions.
	async function hello() {
		return greeting = await Promise.resolve("Hello");
};

Let's take a look at how using the notation async and await can be used in replace of the chain functions with the use of then() method.

fetch with chains of then methods

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

fetch with async/await

const response = await fetch('http://example.com/movies.json')
const jsonReponse = await response.json
console.log(data));

This syntax may seem slightly more wordy but can come in handy as you build more complicated projects.

Fork me on GitHub