Why Async?
JavaScript is single-threaded. To avoid blocking the UI while waiting for network requests, file reads, or timers, we use asynchronous code.
Promises
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => resolve("Data loaded!"), 1000);
});
fetchData
.then(data => console.log(data)) // Data loaded!
.catch(err => console.error(err));
async / await
async function loadUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
const user = await response.json();
return user;
} catch (error) {
console.error("Failed to load user:", error);
}
}
Parallel Requests
async function loadAll() {
const [users, posts] = await Promise.all([
fetch("/api/users").then(r => r.json()),
fetch("/api/posts").then(r => r.json()),
]);
console.log(users, posts);
}