June 18, 2020 5 min read

Understanding Async / Await in JavaScript ES6

Before we begin, let's discuss the basics of async / await. First, to make an asynchronous function you must add the async keyword in front of the function. This allows the function the capability to know there may be an await keyword being used to invoke the call and to return a promise rather than directly returning a value. Second, await can be put in front of any async promise-based function to pause your code on that line until the promise fulfills, then return the resulting value. In the meantime, other code that may be waiting for a chance to execute gets to do so.

Let's get started

Okay, now that's out the way. Let's get to coding! For this example, I will make use of the Star Wars API.


The first thing we want to do is set up a few variables to get us started.

// star wars endpoint
const apiURL = "https://swapi.dev/api/";
// characters dropdown
const characters = document.querySelector(".characters");
// wrapping div
const wrap = document.createElement("div");
// default count
let count = 1;

Fetch Data

Next, let's create our first async function called setCharacters. We want this function to fetch all characters from the Star Wars API and to populate the characters dropdown right after the page loads.

async function setCharacters() {
  const response = await fetch(`${apiURL}people/`);
  const data = await response.json();
  characters.add(new Option("Select a Name", ""));
  data.results.map((elt) => {
    const { name } = elt;
    const option = document.createElement("option");
    option.value = count++;
    option.innerText = name;

Show Details

Now that we have the dropdown populated with characters. We need to create another async function that will display their details once selected.

async function setDetails(id) {
  const response = await fetch(`${apiURL}people/${id}/`);
  const data = await response.json();
  const {
  } = data;
  const planet = await getPlanet(homeworld.slice(-2));
  wrap.innerHTML = `
        <li>Fullname: ${name}</li>
        <li>Height: ${height}</li>
        <li>Mass: ${mass}</li>
        <li>Hair Color: ${hair_color}</li>
        <li>Skin Color: ${skin_color}</li>
        <li>Eye Color: ${eye_color}</li>
        <li>Birth Year: ${birth_year}</li>
        <li>Gender: ${gender}</li>
        <li>Homeworld: ${planet.name} - Population ${planet.residents.length}</li>

Wrapping it up

Okay, we now have two functions. One to populate our dropdown with the Star Wars characters and one function to display their information once selected. We now need to add an event listener for the setDetails function to the dropdown to wait for a change.

characters.addEventListener("change", (e) => {
  const id = e.currentTarget.options[e.currentTarget.selectedIndex].value;
  wrap.innerText = "";

Complete Code

You can find the complete working example on my codepen: https://codepen.io/decodesalot/pen/jOPBeBN