async/await in JavaScript
⏳ What is async/await?
async and await are syntactic features introduced in ES2017 that simplify working with Promises. They allow writing asynchronous code that looks and behaves like synchronous code.
>>“Async/await makes asynchronous code easier to read and reason about.”
📦 The async Keyword
Declaring a function with async automatically wraps its return value in a Promise.
Code Snippet
async function greet() {
return "Hello!";
}
greet().then((msg) => console.log(msg)); // 👉 Hello!⏱ The await Keyword
Use await to pause execution until a Promise resolves. It can only be used inside an async function.
Code Snippet
async function getData() {
const response = await fetch("https://api.example.com/data");
const json = await response.json();
console.log(json);
}Note
💡 await pauses the function, but not the whole program — other tasks still run.
🚀 Example: Async/Await Flow
Chained Promises → Async/Await
// Old Promise way
fetch("https://api.example.com/user")
.then(res => res.json())
.then(data => console.log(data));
// New async/await way
async function loadUser() {
const res = await fetch("https://api.example.com/user");
const user = await res.json();
console.log(user);
}🛑 Handling Errors with try...catch
Since await can throw, use try...catch blocks for error handling.
Code Snippet
async function fetchProduct() {
try {
const res = await fetch("/api/product");
const data = await res.json();
console.log(data);
} catch (err) {
console.error("❌ Error fetching product:", err);
}
}🧵 Running Multiple Awaits in Parallel
Use Promise.all() to await multiple tasks concurrently:
Code Snippet
async function getAllData() {
const [user, posts] = await Promise.all([
fetch("/user").then(r => r.json()),
fetch("/posts").then(r => r.json()),
]);
console.log(user, posts);
}⚠️ Don’t Use await in Loops Unnecessarily
Doing await inside a loop causes sequential execution. Instead, collect promises and await them together.
Code Snippet
// ❌ Slow
for (const id of ids) {
await fetchItem(id);
}
// ✅ Fast
await Promise.all(ids.map(fetchItem));🧠 Summary
- async makes a function return a Promise.
- await pauses the async function until the Promise resolves.
- Use try...catch to handle errors in async functions.
- Prefer Promise.all() for parallel async operations.
🔗 References
>>“Write asynchronous code that reads like synchronous code — that’s the power of async/await.”