I’m new to JavaScript async/await and can’t seem to understand why my browser wouldn’t display anything when I use async and await with JS modules – Kindly suggest!
pokeUtils.js
export async function fetchPokemon(){
try{
const pokeName = document.getElementById("pokemonName").value.toLowerCase();
if (!pokeName) {
throw new Error("Please enter a Pokemon name!");
}
const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokeName}`);
if(!response.ok || response.status === 404){
throw new Error("Could not fetch Pokemon! - " + response.status)
}
const data = await response.json();
return data;
}
catch(error){
console.error(error)
}
}
main.js
import { fetchPokemon } from "./pokeUtils";
document.getElementById("fetchButton").addEventListener("click", async () => {
try {
const data = await fetchPokemon();
const pokemonSprite = data.sprites.front_default;
const imgElement = document.getElementById("pokemonImg");
imgElement.src = pokemonSprite;
imgElement.style.display = "block";
}
catch (error) {
console.log(error);
}
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fetch a Pokemon!</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<input type="text" id="pokemonName" placeholder="Enter Pokemon Name?">
<button id="fetchButton">Fetch Pokemon!</button>
<img src="" alt="Pokemon Sprite" id="pokemonImg" style="display: none;">
<script type="module" src="main.js"></script>
</body>
</html>
Expecting to see the Pokemon Sprite to be displayed on the front end but it doesn’t display anything and the console is blank
New contributor
user22975319 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.