JavaScript Async/Await Example with Star Wars API

Making asynchronous programming easier with async and await in JavaScript. In this article I will cover an example of using the star wars api to fetch data and depending on the user, returns their details. But first, lets go over 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.

The real advantages of async functions comes to life when you combine it with the await keyword I keep referencing. The reason I keep mentioning await with async is because the await keyword only works inside an async function. A good note for await is when you can use them on any function that returns a promise, including web API functions.

Below I made use of the Star Wars API demonstrating a few async functions that will immediately populate an option set with list of star war characters. Then I have an event set for once the value changes in the dropdown to then fetch the details of the user selected. One good example to pay attention to in the code is once you select a user from the dropdown list, look at the function that returns the details. I hope this gives you a better understanding of what async functions are and how you can use the await keyword.

Example:

"use strict";

document.addEventListener("DOMContentLoaded", () => {
  
  const apiURL = "https://swapi.dev/api/";
  const characters = document.querySelector(".characters");
  const wrap = document.createElement("div");
  let count = 1;
  
  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;
      characters.appendChild(option);
    }); 
    
  }
  
  async function getPlanet(id){
    
    const response = await fetch(`${apiURL}planets/${id}`);
    const data = await response.json();
    return data;
    
  }

  async function setDetails(id) {
    
    const response = await fetch(`${apiURL}people/${id}/`);
    const data = await response.json();
    
    const { name, height, mass, hair_color, skin_color, eye_color, birth_year, gender, homeworld } = data;
    const planet = await getPlanet(homeworld.slice(-2));
    
      wrap.innerHTML = `
      <ul>
        <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>
      </ul>
      `;
      characters.after(wrap)
  }

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

Or take a look on codepen: https://codepen.io/decodesalot/pen/jOPBeBN?editors=1010


Derrick Reeder JS/JQuery May 13, 2020

Related Posts

Lorem Ipsum Dolor

Autem voluptatem aperiam nostrum odit sapiente totam distinctio fuga inventore quaerat.

Read More

Lorem Ipsum Dolor

Autem voluptatem aperiam nostrum odit sapiente totam distinctio fuga inventore quaerat.

Read More

Lorem Ipsum Dolor

Autem voluptatem aperiam nostrum odit sapiente totam distinctio fuga inventore quaerat.

Read More