Khachatryan-dev

Fetch API

Fetch API — modern Promise-based method, examples

Aram
Khachatryan

Fetch API — A Modern Promise-based Method for HTTP Requests


The Fetch API is presented as a modern replacement for XMLHttpRequest, designed for simpler, more convenient and flexible implementation of network requests. It's a basic Promise-based API that allows writing shorter, more readable and cleaner asynchronous JavaScript code using async/await syntax.


Details about Fetch API:


  • Automatically returns a Promise that resolves when a Response object is received
  • The Response object provides multiple methods for parsing data (json(), text(), blob(), arrayBuffer(), etc.)
  • Supports a wide spectrum of HTTP methods, headers, bodies, and CORS policy configuration
  • Fully supports async/await syntax, making code flow management easier

Let's consider a simple example for making a GET request and receiving a JSON response:


     fetch("https://jsonplaceholder.typicode.com/posts/1") 
            .then(response => {
                if (!response.ok) {
                    throw new Error("Network response was not ok " + response.statusText); 
                }
                
                return response.json(); 
            })
            .then(data => { console.log("Response data:", data); })
            .catch(error => { console.error("Fetch error:", error); });

Or with async/await syntax:


     async function fetchPost() {
            try {
                const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
                if (!response.ok) { throw new Error("Network response was not ok " + response.status); }
                const data = await response.json(); console.log("Response data:", data); 
            } catch (error) {
                console.error("Fetch error:", error); 
            } 
        }
        fetchPost();

Advantages of Fetch API:


  • Shorter and cleaner-looking code thanks to Promises and async/await
  • Good integration with modern JavaScript tools and async functions
  • Easy to develop and maintain in large projects
  • Wide support in modern browsers

Limitations and considerations:


  • Fetch doesn't provide automatic request timeout, which needs to be managed manually
  • Doesn't provide some convenient events like XHR's progress events
  • CORS policies need to be properly configured on the server side, otherwise blocking may occur

Overall, the Fetch API offers a convenient, modern and "clean" way to implement HTTP requests, making JavaScript network code more readable and stable.


Next, we'll conduct a comparative analysis between XMLHttpRequest and Fetch API to understand their advantages and disadvantages and when each method is preferable to use.




Buy me a coffee
  • 0
  • 2

Discover More Content

Comments
No data
No comments yet. Be the first to comment!
Leave a Comment
You must be logged in to leave a comment.Login