Understanding Async/Await in JavaScript
Ad
What is Async/Await?
async/await is syntax (introduced in ES2017) that lets you write asynchronous, Promise-based code as if it were synchronous — no .then() chains, no callback pyramids.
From Promises to Async/Await
// Promise style
function getUser() {
return fetch("/api/user")
.then(res => res.json())
.then(user => console.log(user))
.catch(err => console.error(err));
}
// async/await style — same thing, cleaner
async function getUser() {
try {
const res = await fetch("/api/user");
const user = await res.json();
console.log(user);
} catch (err) {
console.error(err);
}
}
Key Rules
awaitcan only be used inside anasyncfunction (or top-level in ES modules).awaitpauses the function until the Promise resolves, then returns its value.- An
asyncfunction always returns a Promise. - Use
try/catchfor error handling instead of.catch().
Running Tasks in Parallel
// ❌ Slow — runs one after another (sequential)
const a = await fetchA(); // 1s
const b = await fetchB(); // 1s → total 2s
// ✅ Fast — runs at the same time
const [a, b] = await Promise.all([fetchA(), fetchB()]); // total 1s
Common Mistake
Forgetting await means you get the Promise object instead of its value:
const data = fetch("/api"); // ❌ data is a Promise
const data = await fetch("/api"); // ✅ data is the Response
FAQs
Is async/await faster than Promises?
No — it compiles to the same Promise machinery. It is purely about readability.
How do I handle errors for multiple awaits?
Wrap them in a single try/catch, or use Promise.allSettled() when you want every result regardless of failures. More in our JavaScript section.
