Write clean, readable asynchronous code using ES8 async functions and sequential await expressions.
Learn how variables act as labeled containers for data using const, let, and var to manage lexical scope and reassignment safely in modern applications.
ES8 introduced async and await, syntactic sugar built directly on top of Promises.
It allows you to write asynchronous code that reads sequentially like synchronous code, avoiding long .then() chains.
Mark a function as async to allow pausing execution at any await expression until the Promise settles:
function fetchUser(id) {
return Promise.resolve({ id: id, name: "Alex" });
}
async function loadUserProfile() {
console.log("Fetching user...");
// Execution pauses here until Promise resolves
const user = await fetchUser(42);
console.log(`Loaded: ${user.name}`);
return user;
}
loadUserProfile();
Avoid sequential waterfalls when requests are independent:
// Slow Waterfall (Sequential)
// const user = await fetchUser();
// const posts = await fetchPosts();
// Fast Parallel Execution!
async function loadDashboard() {
const [user, posts] = await Promise.all([fetchUser(), fetchPosts()]);
return { user, posts };
}
async Keyword: Using await outside an async function in older environments throws a syntax error.Promise.all()!Use async/await for clean async logic. Next, let's catch runtime errors with try...catch!