Skip to content

Instantly share code, notes, and snippets.

@ross-u
Last active February 1, 2023 15:15
Show Gist options
  • Save ross-u/16466b5b3e884fdb58bf47fae590133a to your computer and use it in GitHub Desktop.
Save ross-u/16466b5b3e884fdb58bf47fae590133a to your computer and use it in GitHub Desktop.
JS | Promises & Async/Await - Code Along Starter Code

JS | Promise & async/await


Pokedex - Code Along examples



Step 1: Create file structure

mkdir promises-and-async-await

cd promises-and-async-await

touch index.html style.css promiseExample.js asyncAwaitExample.js wrongAsyncAwaitExample.js

code .

Step 2: Paste the starter code content from the below files index.html & style.css.


const body = document.querySelector('body');
const pokemonsList = document.getElementById('pokemon-list');
// API DOCS - https://pokeapi.co/
console.log('ASYNC AWAIT EXAMPLE');
const loadPokemons = async () => {
try {
let response = await fetch('https://pokeapi.co/api/v2/pokemon/?limit=100'); // Asynchronous operation - must be awaited
console.log('response', response);
const data = await response.json(); // Asynchronous operation - must be awaited
console.log('DATA ', data);
data.results.forEach((pokemon, index) => {
const listItem = document.createElement('li');
const name = document.createTextNode(`${index + 1} - ${pokemon.name}`);
listItem.appendChild(name);
pokemonsList.appendChild(listItem);
listItem.addEventListener('click', event => {
selectPokemon(event.target);
});
});
} catch (error) {
console.error('Error fetching the Pokemons', error);
}
};
const selectPokemon = listItem => {
const pokemonIndex = Number.parseInt(listItem.innerHTML);
let nameOfSelected = document.getElementById('name');
const imageOfSelected = document.getElementById('selected-image');
nameOfSelected.innerHTML = listItem.innerHTML.toUpperCase();
nameOfSelected.style.visibility = 'visible';
nameOfSelected.style.display = 'visible';
imageOfSelected.src = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemonIndex}.png`;
};
loadPokemons();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Pokedex List</title>
</head>
<body>
<nav>
<img id="logo" src="https://assets.pokemon.com/assets/cms2/img/misc/gus/buttons/logo-pokemon-79x45.png" alt="">
</nav>
<main>
<header>
<h3> JS Promises & async/await </h3>
</header>
<section>
<h4 id="name"></h4>
<img src="" id="selected-image">
</section>
<ul id="pokemon-list"></ul>
</main>
<script src="./promiseExample.js"></script>
<!-- <script src="./asyncAwaitExample.js"></script> -->
<!-- <script src="./wrongAsyncAwaitExample.js"></script> -->
</body>
</html>
// SAVE REFERENCE TO THE DOM ELEMENTS WE WILL USE
const body = document.querySelector('body');
const pokemonsList = document.getElementById('pokemon-list');
console.log('PROMISE EXAMPLE');
// API DOCS - https://pokeapi.co/
const loadPokemons = () => {
// CREATE A FETCH GET REQUEST
fetch('https://pokeapi.co/api/v2/pokemon/?limit=100') // Asynchronous operation - must be awaited
.then(response => {
console.log('response', response);
// PARSE THE RESPONSE BODY
const parsedData = response.json(); // Asynchronous operation - must be awaited
return parsedData;
})
.then(data => {
console.log('DATA ', data);
// ITERATE OVER JSON DATA AND CREATE A LIST
data.results.forEach((pokemon, i) => {
const listItem = document.createElement('li');
const name = document.createTextNode(`${i + 1} - ${pokemon.name}`);
listItem.appendChild(name);
pokemonsList.appendChild(listItem);
// ADD "ON CLICK" EVENT LISTENER TO RENDER SELECTED POKEMON
listItem.addEventListener('click', event => {
selectPokemon(event.target);
});
});
})
.catch(error => {
console.error('Error fetching the Pokemons', error);
});
};
const selectPokemon = listItem => {
const pokemonIndex = Number.parseInt(listItem.innerHTML);
const imageOfSelected = document.getElementById('selected-image');
let nameOfSelected = document.getElementById('name');
nameOfSelected.innerHTML = listItem.innerHTML.toUpperCase();
nameOfSelected.style.visibility = 'visible';
imageOfSelected.src = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemonIndex}.png`;
};
loadPokemons();
body {
margin: 0;
}
nav {
background-color: rgb(51, 51, 146);
padding: 5px 20px
}
main {
padding: 20px;
}
#logo {
height: 50px;
}
#name {
visibility: hidden;
display: inline;
padding: 10px 25px;
margin-bottom: 0px;
border: 1px solid rgb(25, 25, 80);
border-radius: 4px;
color: rgb(51, 51, 146);
background-color: rgb(255, 255, 203);
}
#selected-image {
display: block;
padding: 10px 20px;
}
#pokemon-list li {
list-style: none;
padding: 20px 60px;
border: 1px solid black;
margin-bottom: 10px;
border-radius: 4px;
text-align: center;
cursor: pointer;
}
const body = document.querySelector('body');
const pokemonsList = document.getElementById('pokemon-list');
// API DOCS - https://pokeapi.co/
console.log('WRONG - ASYNC AWAIT EXAMPLE');
const loadPokemons = async () => {
let data;
try {
let response = await fetch('https://pokeapi.co/api/v2/pokemon/?limit=100'); // Asynchronous operation - must be awaited
console.log('response', response);
data = await response.json(); // Asynchronous operation - must be awaited
} catch (error) {
console.error('Error fetching the Pokemons', error);
}
return data; // WRONG APPROACH - Async function always returns a pending promise by default
};
const selectPokemon = listItem => {
const pokemonIndex = Number.parseInt(listItem.innerHTML);
let nameOfSelected = document.getElementById('name');
const imageOfSelected = document.getElementById('selected-image');
nameOfSelected.innerHTML = listItem.innerHTML.toUpperCase();
nameOfSelected.style.visibility = 'visible';
nameOfSelected.style.display = 'visible';
imageOfSelected.src = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemonIndex}.png`;
};
let pokemons = loadPokemons();
console.log('POKEMONS ???', pokemons); // Promise {<pending>}
pokemons.results.forEach((pokemon, index) => {
const listItem = document.createElement('li');
const name = document.createTextNode(`${index + 1} - ${pokemon.name}`);
listItem.appendChild(name);
pokemonsList.appendChild(listItem);
listItem.addEventListener('click', event => {
selectPokemon(event.target);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment