async / await
Write asynchronous code that reads like synchronous code
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
async/await is over Promises that makes async code read top-to-bottom like synchronous code.
async function — always returns a Promise: ``javascript async function getUser(id) { const res = await fetch(/api/users/${id}); const user = await res.json(); return user; // wrapped in a resolved Promise automatically }
await — pauses execution inside the async function until the Promise settles. It is — it does NOT block the entire program.
Error handling with try/catch:
javascript async function loadData() { try { const res = await fetch('/api/data'); if (!res.ok) throw new Error(HTTP ${res.status}); const data = await res.json(); return data; } catch (err) { console.error('Failed:', err.message); } }
Parallel with async/await:
javascript // Sequential (slow — each waits for the previous) const a = await fetchA(); const b = await fetchB(); // Parallel (fast — both start at the same time) const [a, b] = await Promise.all([fetchA(), fetchB()]);
await is only valid inside async functions (or at the top level of modules in modern JS).
Examples
Fetch with async/await vs Promise chain
async/await is syntactic sugar — same Promises underneath
// Promise chain
fetch('/api/users/1')
.then(r => r.json())
.then(u => console.log(u.name));
// async/await — same thing, easier to read
async function showUser() {
const res = await fetch('/api/users/1');
const user = await res.json();
console.log(user.name);
}
showUser();Parallel requests
Use Promise.all inside async functions to avoid sequential awaits
async function dashboard(userId) {
const [profile, posts, notifications] = await Promise.all([
fetch(`/api/users/${userId}`).then(r => r.json()),
fetch(`/api/users/${userId}/posts`).then(r => r.json()),
fetch(`/api/users/${userId}/notifications`).then(r => r.json()),
]);
return { profile, posts, notifications };
}How well did you understand this?
Next in JavaScript Core
ES Modules