Introduced in ECMAScript 2017 (ES8), async/await is elegant syntactic sugar built on top of native JavaScript Promises. It allows asynchronous code to be structured, read, and reasoned about just like standard synchronous code, completely eliminating .then() callback chaining.
async: Placed before function declarations or arrow functions. Guarantees the function returns a Promise.await: Can only be used inside async functions. Pauses function execution until the awaited Promise resolves or rejects.async function loadUserDashboard(userId) {
try {
console.log("Initiating dashboard fetch...");
// Code pauses cleanly at each 'await' until resolved:
const user = await fetchUserData(userId);
const preferences = await fetchUserPreferences(user.id);
console.log(`Dashboard ready for ${user.name}`, preferences);
return { user, preferences };
} catch (error) {
// Any rejection in either fetch lands here cleanly!
console.error("Dashboard failed to load:", error.message);
throw error; // Re-throw or handle gracefully
}
}
A common beginner mistake is awaiting independent promises sequentially, doubling network wait times:
// BAD PRACTICE: Sequential (Waterfall Bottleneck - Takes 4 seconds!)
async function loadSlow() {
const students = await fetchStudents(); // Takes 2 seconds
const courses = await fetchCourses(); // Takes 2 seconds (waited unnecessarily!)
return { students, courses };
}
// BEST PRACTICE: Parallel with Promise.all (Takes only 2 seconds total!)
async function loadFast() {
// Initiate BOTH network requests concurrently:
const studentsPromise = fetchStudents();
const coursesPromise = fetchCourses();
// Await both simultaneously:
const [students, courses] = await Promise.all([studentsPromise, coursesPromise]);
return { students, courses };
}
Exam Question: "What is the equivalent Promise chain of an async/await function?"
async function getRank() {
const score = await calculateScore();
return score > 90 ? "Rank 1" : "Pass";
}
Equivalent Under the Hood Promise Form:
function getRank() {
return calculateScore().then(score => {
return score > 90 ? "Rank 1" : "Pass";
});
}
How do modern web applications fetch live data from REST APIs across the internet? Proceed to: JavaScript Fetch API: HTTP Requests & REST Data →
Accelerate your JavaScript mastery by studying these tightly connected core tutorials:
The underlying promise primitives of async/await.
Real-world data fetching from REST backends.
Catching asynchronous network rejections.
Microtask scheduling during await pauses.