⚡IntermediateAsync JavaScript
Async/Await
Write asynchronous code that reads like synchronous code using async functions and the await keyword.
Overview
Async/await is syntactic sugar over Promises, introduced in ES2017. It lets you write asynchronous code that looks and reads almost exactly like synchronous code no .then() chains, no callback nesting, just straight top-to-bottom logic.
An async function always returns a Promise. Inside it, you can use the await keyword in front of any Promise to pause execution of that function until the Promise settles. The function pauses but not the thread. Other code continues to run; the event loop keeps moving. When the awaited Promise resolves, execution of the async function resumes from where it left off.
Error handling in async functions uses familiar try/catch blocks instead of .catch(). This makes code flow more readable and allows handling both sync and async errors in the same structure. Async/await is now the dominant pattern for writing async JavaScript and is what you will encounter in virtually every modern JavaScript codebase.
Key Points
- •async before a function makes it return a Promise automatically
- •await pauses the async function until the Promise resolves the thread is NOT blocked
- •await can only be used inside async functions (or at the top level of ES modules)
- •try/catch works naturally with await to handle rejected Promises
- •Multiple awaits in sequence run one after another use Promise.all for parallel execution
- •async functions return Promise<undefined> if no value is returned, or Promise<value> if a value is returned
- •An async function that throws synchronously rejects the returned Promise
- •Top-level await is available in ES modules (not in CommonJS require() files)
Examples
Basic async/await with error handling
async function getUser(id) {
// Simulate an API call
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id === 0) reject(new Error("User not found"));
else resolve({ id, name: "Alice" });
}, 200);
});
}
async function main() {
try {
const user = await getUser(1);
console.log("User:", user.name); // User: Alice
const missing = await getUser(0); // throws
console.log("Never reached");
} catch (err) {
console.error("Error:", err.message); // User not found
}
}
main();Sequential vs parallel with await
function wait(ms, value) {
return new Promise(resolve => setTimeout(() => resolve(value), ms));
}
// Sequential: total time ~600ms
async function sequential() {
const a = await wait(300, "A");
const b = await wait(300, "B");
console.log(a, b);
}
// Parallel: total time ~300ms
async function parallel() {
const [a, b] = await Promise.all([
wait(300, "A"),
wait(300, "B"),
]);
console.log(a, b);
}
sequential(); // runs both sequentially
parallel(); // runs both at the same timeWhen async operations are independent, always use Promise.all instead of sequential awaits it is significantly faster.
Real-world fetch with async/await
async function fetchPost(id) {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const post = await response.json();
return post;
}
async function run() {
try {
const post = await fetchPost(1);
console.log("Title:", post.title);
} catch (err) {
console.error("Failed:", err.message);
}
}
run();fetch() does not reject on HTTP error codes like 404 you must check response.ok yourself.
Common Mistakes
- Using await without async on the enclosing function this is a syntax error
- Running independent awaits in sequence when Promise.all would be faster
- Forgetting try/catch an uncaught rejected await crashes Node.js and causes unhandled rejection warnings
- Returning await inside try/catch write "return await fn()" not "return fn()" if you want catch to handle the rejection
Note
When you need the result of multiple independent async operations, reach for Promise.all. Only use sequential awaits when each step genuinely depends on the result of the previous one.
Exercises
Write JavaScript code to solve each exercise. Run it and check your output.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4