⚡ Lesson 19 of 30
Promises & Async/Await
Write clean asynchronous code using Promises, async functions, await, and Promise combinators.
Why Asynchronous?
JavaScript is single-threaded. For operations that take time (network, disk), we use async patterns so the UI doesn't freeze:
// Synchronous — blocks everything
// const data = readFile("big.txt"); // would freeze the UI
// Asynchronous — non-blocking
setTimeout(() => console.log("After 1 second"), 1000);
console.log("This runs first!");
Creating Promises
A Promise represents a value that will be available in the future:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
const fetchUser = id =>
new Promise((resolve, reject) => {
if (id > 0) resolve({ id, name: "Alice" });
else reject(new Error("Invalid ID"));
});
fetchUser(1)
.then(user => console.log(user.name)) // "Alice"
.catch(err => console.error(err.message));
async / await
async/await makes promise-based code read like synchronous code:
async function getUser(id) {
try {
const user = await fetchUser(id);
console.log(`Got: ${user.name}`);
return user;
} catch (error) {
console.error("Failed:", error.message);
}
}
getUser(1);
Promise.all & Promise.race
Run multiple promises in parallel:
async function loadDashboard() {
const [user, posts, settings] = await Promise.all([
fetchUser(1),
fetchPosts(1),
fetchSettings(1),
]);
console.log(user, posts, settings);
}
// Race — use whichever resolves first
const fastest = await Promise.race([fetchA(), fetchB()]);
Promise.allSettled
Like Promise.all but waits for every promise — even rejected ones:
const results = await Promise.allSettled([
Promise.resolve("success"),
Promise.reject("error"),
Promise.resolve("another"),
]);
results.forEach(r => {
if (r.status === "fulfilled") console.log("✓", r.value);
else console.log("✗", r.reason);
});