Asynchronous JavaScript — Solutions
Async is not about speed.
It’s about control, UX, and resilience.
“Real apps assume things will fail — and handle it gracefully.”
⏳ Challenge 1 — Loading & Error Handling
Goals:
- Show loading text
- Handle errors properly
JavaScript
const statusText = document.querySelector("#status");
const card = document.querySelector(".card");
async function fetchUser() {
statusText.textContent = "Loading...";
card.innerHTML = "";
try {
const res = await fetch("https://randomuser.me/api/");
if (!res.ok) throw new Error("Network error");
const data = await res.json();
const user = data.results[0];
card.innerHTML = `
${user.name.first} ${user.name.last}
${user.email}
`;
statusText.textContent = "";
} catch (error) {
statusText.textContent = "Failed to load data ❌";
}
}
fetchUser();
Loading state keeps users calm. Error handling keeps apps alive.
🔁 Challenge 2 — Refetch with Button
Goal:
- Click button → fetch new data
JavaScript
const refreshBtn = document.querySelector("#refreshBtn");
refreshBtn.addEventListener("click", () => {
fetchUser();
});
Same logic. Different trigger.
🧬 Challenge 3 — Filter User by Gender
Goal:
- Fetch based on selected gender
- Render filtered data
JavaScript
const genderSelect = document.querySelector("#gender");
async function fetchUserByGender() {
const gender = genderSelect.value;
statusText.textContent = "Loading...";
card.innerHTML = "";
try {
const res = await fetch(
`https://randomuser.me/api/?gender=${gender}`
);
const data = await res.json();
const user = data.results[0];
card.innerHTML = `
${user.name.first} ${user.name.last}
${user.email}
${user.gender}
`;
statusText.textContent = "";
} catch {
statusText.textContent = "Something went wrong ❌";
}
}
genderSelect.addEventListener("change", fetchUserByGender);
Now your app reacts to user input + API data. This is dynamic UI.
🧠 Why This Module Is a Big Deal
- You handled async state
- You protected UI from failures
- You reused logic efficiently
- You filtered real API data
This is no longer tutorial-level code. This is production mindset.