Core Async Await Rules
An async function always returns a promise.
await pauses inside async functions until promise settles. Rejections throw errors at await line.
Use try/catch for explicit error handling and predictable user-facing behavior.
JavaScript Tutorial
async/await makes asynchronous code easier to read and maintain. It is built on promises and is widely used in modern JavaScript.
Why this matters
Most apps depend on async operations such as API calls and storage reads. Async/await clarity reduces error-prone callback chains.
An async function always returns a promise.
await pauses inside async functions until promise settles. Rejections throw errors at await line.
Use try/catch for explicit error handling and predictable user-facing behavior.
Sequential await is readable and best when second task depends on first output.
If tasks are independent, Promise.all should be preferred for parallel speed.
async function loadUserPosts(userId) {
try {
const userRes = await fetch("https://jsonplaceholder.typicode.com/users/" + userId);
const user = await userRes.json();
const postRes = await fetch("https://jsonplaceholder.typicode.com/posts?userId=" + userId);
const posts = await postRes.json();
console.log(user.name, posts.length);
} catch (error) {
console.error("Load failed:", error.message);
}
}
loadUserPosts(1);Readable flow where the second request depends on userId.
async function loadDashboard() {
try {
const [usersRes, postsRes] = await Promise.all([
fetch("https://jsonplaceholder.typicode.com/users"),
fetch("https://jsonplaceholder.typicode.com/posts"),
]);
const [users, posts] = await Promise.all([usersRes.json(), postsRes.json()]);
console.log(users.length, posts.length);
} catch (error) {
console.error("Dashboard error:", error.message);
}
}
loadDashboard();Parallel requests reduce total waiting time for independent calls.
async function loadConfig() {
try {
const res = await fetch("/api/config");
if (!res.ok) throw new Error("Config request failed");
return await res.json();
} catch {
return { theme: "light", beta: false };
}
}
loadConfig().then(console.log);Fallback patterns avoid complete UI breakage.
Wrap logic in async function or supported top-level module context.
Use try/catch or handle rejection with .catch.
Use Promise.all when tasks do not depend on each other.
It is usually easier to read. Under the hood it still uses promises.
Yes, but execution becomes sequential. Use Promise.all for parallel behavior where safe.
An error is thrown at await line and should be handled in try/catch.
They return promises by default; return explicit data shape for consistency.