Lesson 33 / 38
async/await & the Fetch API
Writing async code that reads like sync code, and making a real request.
async/await basics
await pauses the function until the promise settles, without blocking the rest of the app.
async function getData() {
const result = await fetchData();
console.log(result);
}Sugar over Promises
async/await is syntax sugar over Promises — it lets asynchronous code read top-to-bottom like synchronous code.
Fetching data
fetch() returns a promise that resolves to a response; call .json() to parse the body.
async function getUser() {
try {
const response = await fetch("https://api.example.com/user/1");
const data = await response.json();
console.log(data);
} catch (err) {
console.log("Fetch failed:", err.message);
}
}Always handle errors
Wrap await in try/catch — a rejected promise inside an async function throws, and an unhandled rejection can crash a Node process.