appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Promises and async/await

Lesson 2 of 412 minIntermediate

Handle work that finishes later without freezing the page.

JavaScript runs one task at a time. Slow things (network requests, timers) are started and finish later. A Promise represents that future result: pending, then fulfilled with a value or rejected with an error.

fetch("https://api.example.com/users/1")
  .then((res) => res.json())
  .then((user) => console.log(user.name))
  .catch((err) => console.error("failed", err));

async and await write the same thing so it reads top to bottom.

async function loadUser(id) {
  const res = await fetch(`https://api.example.com/users/${id}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

try {
  const user = await loadUser(1);
  console.log(user.name);
} catch (err) {
  console.error("could not load", err);
}

Carefulfetch only rejects on network failures. A 404 or 500 response is a successful fetch. Always check res.ok before you use the body.

Several at once

const [a, b] = await Promise.all([loadUser(1), loadUser(2)]);   // runs in parallel
const results = await Promise.allSettled([loadUser(1), loadUser(999)]);   // never throws

Awaiting in a loop runs requests one after another. When the requests do not depend on each other, start them together with Promise.all.

NoteCancel a request with AbortController: pass signal to fetch and call controller.abort() (for example when the user leaves the page or types a new search).

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. fetch returns a 404 response. What happens to the promise?
2. How do you run two independent requests at the same time?
3. What does await do inside an async function?

Key terms