intermediate

Asynchronous JavaScript: Promises, async/await and fetch

Handle code that waits: the event loop, callbacks and promises, async/await, fetching JSON from an API, HTTP errors, loading and error states, cancelling requests and CORS. Practise with a simulated API that succeeds and fails.

50 min

1. Code that waits

Many things take time: loading data from a server, reading a file, waiting for a timer or a user click. JavaScript runs on a single thread, so if it simply waited, the whole page would freeze. Instead it starts the slow task, carries on, and handles the result when it arrives.

The mechanism is the event loop: JavaScript runs the current code to the end, then picks the next ready task from a queue (a finished timer, a click, a network response). Because of this, a long synchronous loop freezes the page, while waiting for the network does not.

console.log('1');
setTimeout(() => console.log('2'), 0);    // queued for later, even with 0 delay
console.log('3');
// prints 1, 3, 2

2. Callbacks, then promises

The old way was callbacks: pass a function to be called when done. Nesting them leads to unreadable “callback hell”. A promise represents a value that will exist later, in one of three states: pending, fulfilled (with a value) or rejected (with an error).

fetch('/api/courses')
  .then((res) => res.json())
  .then((courses) => console.log(courses))
  .catch((err) => console.error('Failed:', err));

3. async/await

async/await is promise syntax that reads like ordinary code:

async function loadCourses() {
  const res = await fetch('/api/courses');       // pause here until the response arrives
  const courses = await res.json();              // and here
  return courses;                                // an async function always returns a promise
}
  • await can only be used inside an async function (or at the top level of a module).
  • It pauses only that function; the page stays responsive.
  • Errors become exceptions, so use try / catch / finally.
async function show() {
  statusEl.textContent = 'Loading...';
  try {
    const courses = await loadCourses();
    statusEl.textContent = `Loaded ${courses.length} courses`;
  } catch (err) {
    statusEl.textContent = `Failed: ${err.message}`;
  } finally {
    spinner.hidden = true;            // runs whether it worked or not
  }
}

4. fetch, properly

fetch returns a promise for a Response. Two traps catch every beginner:

  1. fetch does not reject on HTTP errors. A 404 or 500 still resolves. It rejects only if the network fails. So check res.ok:
async function getJson(url, options) {
  const res = await fetch(url, options);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}
  1. Reading the body is also asynchronous: await res.json() (or res.text()).

Sending data:

const res = await fetch('/api/enroll', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ courseId: 42 }),
});

Never put secrets in front-end code or URLs: anyone can read them. Call your own server, which holds the keys.

5. Running things together

// Sequential: total time is the sum
const a = await getJson('/api/a');
const b = await getJson('/api/b');

// Parallel: total time is about the slowest
const [a2, b2] = await Promise.all([getJson('/api/a'), getJson('/api/b')]);

// Do not stop everything because one failed
const results = await Promise.allSettled([getJson('/api/a'), getJson('/api/b')]);
// each result is { status: 'fulfilled', value } or { status: 'rejected', reason }

Also useful: Promise.race (the first to settle) and Promise.any (the first to succeed).

6. Good user experience

Every asynchronous action has more than a happy path. Design all the states:

  • Loading: show a spinner or skeleton, and disable the button so it cannot be clicked twice.
  • Success: show the data.
  • Empty: “No results yet”, not a blank screen.
  • Error: say what happened and offer a retry. Distinguish “you are offline” from “the server had a problem”.

Avoid race conditions: if the user types in a search box, an older, slower response must not overwrite a newer one. Cancel stale requests with AbortController:

let controller;
async function search(q) {
  controller?.abort();                       // cancel the previous request
  controller = new AbortController();
  try {
    const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`, { signal: controller.signal });
    render(await res.json());
  } catch (err) {
    if (err.name !== 'AbortError') showError(err);   // aborting is expected, not an error
  }
}

Also debounce input (wait until the user pauses typing) and always encode values you put in URLs with encodeURIComponent.

7. CORS in one paragraph

Browsers enforce the same-origin policy: a page may read responses only from its own origin (scheme, host and port) unless the other server opts in with CORS headers such as Access-Control-Allow-Origin. If your fetch to another domain shows a CORS error, the browser blocked the response; the request often still reached the server. The fix is on the server (allow your origin), or by calling your own back end, which calls the other API. A browser extension or no-cors mode will not fix it for your users.

8. Timers and other async APIs

setTimeout and setInterval also run later. Always clear intervals you no longer need (clearInterval). Many browser APIs return promises: navigator.clipboard.writeText(), document.fonts.ready, crypto.subtle. Wrap a callback API in a promise when you want to await it:

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await sleep(500);

9. Your turn: load data, handle errors, always finish

The lab provides fakeFetch(url), a simulated server. /api/courses returns three courses; any other address returns a 404. Complete:

  • getJson(url) (an async function): use fakeFetch, throw an Error with the message HTTP <status> when the response is not ok, otherwise return the parsed JSON.
  • show(url, targetId) (an async function): put Loading... in the target element, then on success write Loaded N courses: a, b, c, on failure write Failed: <the error message>, and in a finally block add the class done to the element.
Fetch with loading, error and finally
PREVIEW

Your tasks

  • ○getJson and show are async functions
  • ○The good request shows 'Loaded 3 courses: Networking, Linux, Security'
  • ○The missing endpoint shows 'Failed: HTTP 404'
  • ○finally ran for the successful request (class done)
  • ○finally ran for the failed request too (class done)

10. What you learned

JavaScript never blocks on slow work: it starts it and handles the result later. You use async/await with try/catch/finally, you check response.ok because fetch does not reject on HTTP errors, you design loading, empty and error states, and you cancel stale requests. Next you will organise an interface’s data and rendering into components.

🧪 Want to practise this on your own computer? See how to set up your lab →

🤖

Need clarification? Ask GT

Hi, I'm GT — your AI tutor for Asynchronous JavaScript: Promises, async/await and fetch. What would you like to know?
📝

Knowledge Check

1 of 4

fetch() rejects its promise when the server responds with 404. True or false?

Report a problem

About: /lessons/async-javascript-and-fetch