async/await in JavaScript: A Complete Guide
async/await makes async code look synchronous. Here is the complete guide with examples and pitfalls.
async/await in JavaScript: A Complete Guide
async/await is syntactic sugar over promises. It makes async code look synchronous and is the cleanest way to handle async operations.
async Functions
An async function always returns a promise. If you return a value, it is wrapped in a promise. If you throw, the promise rejects.
async function foo() { return 42; // returns Promise.resolve(42) } foo().then((v) => console.log(v)); // 42
await
await pauses the async function until a promise settles. It returns the fulfilled value or throws the rejection reason.
async function main() { const data = await fetch("/api"); const json = await data.json(); console.log(json); }
Error Handling with try/catch
async function main() { try { const data = await fetch("/api"); const json = await data.json(); console.log(json); } catch (err) { console.error("Error:", err); } }
async Arrow Functions
const foo = async () => { const data = await fetch("/api"); return data.json(); };
Parallel with Promise.all
async function main() { const [user, posts] = await Promise.all([fetchUser(), fetchPosts()]); console.log(user, posts); }
The Takeaway
async functions always return promises. await pauses until a promise settles. Use try/catch for errors. Use Promise.all for parallel operations. async/await is the cleanest way to write async code in modern JavaScript.
Syntactic sugar over promises. async functions always return a promise. await pauses the function until a promise settles, then returns the fulfilled value or throws the rejection reason. It makes async code look synchronous.
Yes. If you return a value, it is wrapped in Promise.resolve. If you throw, it becomes Promise.reject. If you return a promise, it is returned as-is.
Use try/catch around the await calls. If any await rejects, the catch block runs with the rejection reason. try/catch also catches thrown errors inside the try block.
Use Promise.all: const [a, b] = await Promise.all([fetchA(), fetchB()]). Start all promises at once, then await all. This is much faster than sequential await for independent operations.
Yes. async/await is syntactic sugar over promises. An async function returns a promise. await pauses until a promise settles. You can mix await with Promise.all and other promise methods.
Ready to master React completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

