Asynchronous JavaScript: Keep Your UI Alive
JavaScript is single-threaded. If your code waits and freezes, your UI dies.
Modern applications constantly communicate with servers, APIs, and databases. The challenge is making sure users don't experience a frozen interface while waiting for data to arrive.
Sync vs Async
Synchronous
Runs line by line. No patience.
console.log("A");
console.log("B");
console.log("C");Output: A → B → C
Asynchronous
Waits without blocking.
console.log("A");
setTimeout(() => {
console.log("B");
}, 2000);
console.log("C");Output: A → C → B
Callback
A callback is a function called later.
function loadData(callback) {
setTimeout(() => {
callback("Data loaded");
}, 2000);
}
loadData((result) => {
console.log(result);
});Works — but too many callbacks lead to callback hell.
Promise
A promise represents a value that will exist later.
- pending
- fulfilled
- rejected
const getData = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Data loaded");
} else {
reject("Failed to load data");
}
});
getData
.then(result => console.log(result))
.catch(error => console.log(error));Cleaner than callbacks. Still readable.
async / await
Looks synchronous. Works asynchronously.
async function fetchData() {
try {
const result = await getData;
console.log(result);
} catch (error) {
console.log(error);
}
}This is the modern standard.
Fetch API
Fetch is how JavaScript talks to the internet.
fetch("https://api.example.com/data")
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err));Cleaner with async/await:
async function getData() {
const res = await fetch("https://api.example.com/data");
const data = await res.json();
console.log(data);
}Mini Project — Quote Generator
async function getQuote() {
const res = await fetch("https://api.quotable.io/random");
const data = await res.json();
console.log(data.content);
}Mini Project — Random User
async function getUser() {
const res = await fetch("https://randomuser.me/api/");
const data = await res.json();
const user = data.results[0];
console.log(user.name.first, user.email);
}Mini Project — Display User Card
async function showUser() {
const res = await fetch("https://randomuser.me/api/");
const data = await res.json();
const user = data.results[0];
const card = document.querySelector(".card");
card.innerHTML = `
<img src="${user.picture.large}">
<h3>${user.name.first} ${user.name.last}</h3>
<p>${user.email}</p>
`;
}JavaScript + DOM + API = the complete front-end combination.
Mini Challenges
- Add loading text and error handling
- Add a button to refetch data
- Filter users by gender and display the result
