Web Development · Module 7 · Lesson 21 min read

async/await & fetch

async/await: promises that read like normal code

JavaScript
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);
  }
}
  • await pauses this function until the promise settles, without blocking the page.
  • await only works inside async functions (and at the top level of ES modules).
  • An async function 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

JavaScript
await fetch("/api/posts", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "Hello" }),
});

Parallel vs sequential

JavaScript
// 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

HTML
<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>