Skip to main content

Command Palette

Search for a command to run...

31. ASYNC | Fetch API in JavaScript

This article will talk about fetch() in javascript.

Updated
3 min read
S
Full-Stack Developer with 4 years' experience, specializing in backend development. Skilled in JavaScript, React, Python, Databases, and AWS. Known for building scalable web apps, leading teams, and maintaining strong client communication. Upskilling in Generative AI.

What is Fetch API?

  • The Fetch API is a modern, promise-based interface used to make HTTP requests to servers.

  • It replaces the older XMLHttpRequest with cleaner, promise-based syntax.

  • It allows you to handle responses asynchronously using Promises.


Basic Syntax

The fetch() method takes the URL of the resource as its first argument and options as its second argument and returns a Promise that resolves to a Response object.

fetch(url, options)
  .then(response => {
    // handle response
  })
  .catch(error => {
    // handle error
  });

Example:

fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.log(error));

How Fetch Works Internally?

  1. fetch() sends a request to the server.

  2. It immediately returns a Promise.

  3. A fetch() promise:

    • Resolves → as soon as response headers are received.

    • Rejects → only on network failures (e.g., DNS issues, offline). It does not reject on HTTP errors like 404 or 500.

  4. Response bodies are streams; once you read them (e.g., via .json()), they are "consumed" and cannot be read again unless cloned.

  5. You process the response using .then().


Understanding the Response Object

The response object contains:

response.ok        // true if status is 200–299 else false
response.status    // HTTP status code
response.headers   // headers

Parsing body:

response.json()   // JSON
response.text()   // plain text
response.blob()   // binary data
💡
We can use only one body parsing method at a time. For e.g., if we have already parsed the response using response.text(), then response.json() won't work.

Example with status check:

fetch("https://api.example.com/data")
  .then(response => {
    if (!response.ok) {
      throw new Error("HTTP error: " + response.status);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error(error));

Important Options in Fetch

fetch(url, {
  method: "GET",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    name: "Shubham",
    age: 25
  }),
  mode: "cors",        // cross-origin requests
  credentials: "include", // send cookies
  cache: "no-cache"
});
💡
JSON.stringify() converts a JavaScript object or value into a JSON string. This process, called serialization, is essential because complex data structures like objects and arrays cannot be sent directly over a network or stored in a text-only file; they must be flattened into a string format.

How Fetch works with Event Loop & Call Stack?

console.log("Start");

fetch("https://api.example.com/data")
  .then(res => res.json())
  .then(data => console.log(data));

console.log("End");

/** Output:
 Start
 End
 {data from API}
*/

/** Flow:
 1. Line 1: The Call Stack executes console.log.
 2. Line 3: fetch() is called and pushed onto the Call Stack. The JavaScript engine delegates it to the browser’s Web API, which sends the HTTP request in the background. Meanwhile, fetch() immediately returns a Promise.
 3. Line 7: The Call Stack executes the second console.log.
 4. Once the browser receives the HTTP response, the Promise is resolved, and the .then() callback is added to the Microtask Queue.
 5. The Event Loop checks if the Call Stack is empty. It first moves tasks from the Microtask Queue (and then from the Callback Queue) to the Call Stack for execution.
*/
console.log("Start");

setTimeout(() => console.log("Timeout"), 0);

fetch("https://api.example.com")
  .then(() => console.log("Fetch"));

console.log("End");

/** Output:
 Start
 End
 Fetch
 Timeout
*/

Happy reading!