Asynchronous JavaScript and the Fetch APILesson 4.3
async/await: writing asynchronous code that reads like synchronous
async function, await keyword, try/catch with async, error handling, async IIFE, top-level await, return values
async / await
async/await is syntactic sugar over Promises. It lets you write asynchronous code in a linear, readable style without chaining.
async function loadUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const user = await response.json();
return user;
} catch (err) {
console.error('Failed to load user:', err.message);
}
}
loadUser(42).then(user => console.log(user));Rules
await can only be used inside an async function. An async function always returns a Promise — even if you return a plain value, it is wrapped automatically.
async function getTwo() { return 2; }
getTwo().then(v => console.log(v)); // 2Top-level await (ES2022)
In ES modules you can use await at the top level without wrapping in an async function:
// module.js
const data = await fetch('/api/config').then(r => r.json());