Codectionary / Developer documentation / JavaScript

Fetch API

The Fetch API provides a modern, promise-based way to make HTTP requests, replacing the older XMLHttpRequest. fetch() returns a promise that resolves to a Response object once headers are received - note that a Response is only considered "ok" if the status is 2xx, so checking response.ok is essential, since fetch() does not reject on HTTP error statuses.

Syntax

fetch(url, options).then(response => response.json())

Examples

Basic GET Request

Fetching and parsing JSON data.

fetch("https://api.example.com/users/1")
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }
    return response.json();
  })
  .then(user => console.log(user))
  .catch(error => console.log("Fetch failed:", error.message));

POST Request with async/await

Sending data with a request, and awaiting the result.

async function createUser(userData) {
  try {
    const response = await fetch("https://api.example.com/users", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(userData)
    });

    if (!response.ok) {
      throw new Error(`Server responded with ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.log("Failed to create user:", error.message);
  }
}

createUser({ name: "Alice", email: "alice@example.com" });

Best practices

  • Always check response.ok before parsing - fetch() only rejects on network failures, not on HTTP error statuses like 404 or 500
  • Wrap fetch calls in try/catch (with async/await) or add a .catch() to handle network failures gracefully
  • Set the Content-Type header explicitly when sending JSON, and remember to JSON.stringify() the body
  • Use AbortController to cancel a fetch request if it is no longer needed, such as when a user navigates away

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation

Async/Await
Async/await is modern JavaScript syntax for handling asynchronous operations, making asynchronous code look and behave like synchronous code. The async keyword marks a function as asynchronous, and await pauses execution until a Promise resolves. This approach makes asynchronous code more readable and easier to understand than traditional Promise chains or callbacks.
Promises
A Promise represents a value that may not be available yet - the eventual result of an asynchronous operation. It exists in one of three states: pending, fulfilled, or rejected. then() handles a successful result, catch() handles an error, and finally() runs regardless of outcome. Promises are the foundation that async/await is built on top of.
Promise.all(), allSettled(), race(), any()
These static methods handle multiple promises at once. Promise.all() waits for every promise to resolve, but rejects immediately if any one fails. allSettled() waits for all to finish regardless of outcome, giving you both successes and failures. race() resolves or rejects as soon as the first promise settles. any() resolves as soon as the first one succeeds, ignoring rejections unless all fail.
Web Workers
Web Workers run JavaScript on a separate background thread, away from the main UI thread, so expensive computations do not freeze the page. Communication between the main script and a worker happens through message passing with postMessage() and the onmessage event handler, rather than shared memory - workers cannot directly access the DOM.