async/await & fetch
async/await: promises that read like normal code
async function loadUser(id) {
try {
const res = await fetch(`https://api.example.com/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const user = await res.json();
return user;
} catch (err) {
console.error("Failed:", err.message);
}
}
awaitpauses this function until the promise settles, without blocking the page.awaitonly works insideasyncfunctions (and at the top level of ES modules).- An
asyncfunction always returns a promise.
⚠️ fetch doesn't fail on HTTP errors
fetch only rejects on network failure. A 404 or 500 still "succeeds", so always check res.ok.
Sending data
await fetch("/api/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Hello" }),
});
Parallel vs sequential
// slow: one after another
const a = await getA();
const b = await getB();
// fast: both at once
const [a2, b2] = await Promise.all([getA(), getB()]);
UI states to handle
Loading (a spinner), success (show data), empty ("No results"), and error (a message plus a Retry button).
Example
<button id="load">Load posts</button>
<p id="status"></p>
<ul id="posts"></ul>
<script>
async function loadPosts() {
const status = document.querySelector("#status");
const list = document.querySelector("#posts");
status.textContent = "Loading…";
list.innerHTML = "";
try {
const res = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=5");
if (!res.ok) throw new Error("HTTP " + res.status);
const posts = await res.json();
posts.forEach((p) => {
const li = document.createElement("li");
li.textContent = p.title;
list.append(li);
});
status.textContent = posts.length + " posts loaded ✅";
} catch (err) {
status.textContent = "Could not load posts: " + err.message;
}
}
document.querySelector("#load").addEventListener("click", loadPosts);
</script>