search
HomeWeb Front-endJS TutorialAn example of how JavaScript uses fetch to complete asynchronous requests

Transmitting information to the server and obtaining information from the server are the top priorities of front-end development, especially under the premise of separation of front-end and back-end. Data interaction between front-end and back-end is a compulsory subject for the front-end. The following article mainly provides We have introduced relevant information about JavaScript using fetch to implement asynchronous requests. Friends in need can refer to it.

Preface

I believe everyone should know that in this AJAX era, if you want to make API and other network requests, you must use XMLHttpRequest or The encapsulated framework makes network requests. The fetch framework produced now is simply designed to provide more powerful and efficient network requests. Although there are some browser compatibility issues at present, when we make some asynchronous requests, we can use fetch to make perfect network requests. Not much to say below, let’s take a look at the detailed introduction.

Let’s first take a look at the native support for fetch in each browser. You can see that the support is not very high. Safari only supports it after 10.1, ios only supports it after 10.3, and IE does not support it at all. Of course, the development of new technologies will always go through this process.


Ajax request

Ordinary Ajax request, send one using XHR A json request generally looks like this:


var xhr = new XMLHttpRequest(); 
xhr.open("GET", url); 
xhr.responseType = 'json'; 
xhr.onload = function(){ 
 console.log(xhr.response); 
}; 
xhr.onerror = function(){ 
 console.log("error") 
} 
xhr.send();

Use fetch to implement:


##

fetch(url).then(function(response){ 
 return response.json(); 
}).then(function(data){ 
 console.log(data) 
}).catch(function(e){ 
 console.log("error") 
})

You can also use async/ The way of await


try{ 
 let response = await fetch(url); 
 let data = await response.json(); 
 console.log(data); 
} catch(e){ 
 console.log("error") 
}

After using await, writing asynchronous code feels as good as synchronous code. Await can be followed by a Promise object, which means waiting for

Promise resolve() before continuing to execute. If Promise is reject() or throws an exception, it will be blocked by an external try... catch capture.

The main advantage of using fetch

#fetch is that the syntax is concise and more Semantic

  • Based on standard Promise implementation, supports async/await

  • Isomorphism is convenient

  • But it also has its shortcomings

The fetch request does not carry cookies by default and needs to be set

fetch(url, {credentials: 'include'})

  • The server will not reject when it returns an error code such as 400 or 500. Only when network errors cause the request to fail to be completed, fetch will be rejected.

  • fetch Syntax:

fetch(url, options).then(function(response) { 
 // handle HTTP response 
}, function(error) { 
 // handle network error 
})

Specific parameter example:


//兼容包 
require('babel-polyfill') 
require('es6-promise').polyfill() 
 
import 'whatwg-fetch' 
 
fetch(url, { 
 method: "POST", 
 body: JSON.stringify(data), 
 headers: { 
 "Content-Type": "application/json" 
 }, 
 credentials: "same-origin" 
}).then(function(response) { 
 response.status //=> number 100–599 
 response.statusText //=> String 
 response.headers //=> Headers 
 response.url //=> String 
 
 response.text().then(function(responseText) { ... }) 
}, function(error) { 
 error.message //=> String 
})

Parameter description

url

Define the resource to be obtained. This might be: a USVString string containing the URL to fetch the resource. A Request object.

options (optional)

A configuration item object, including all settings for the request. Optional parameters are:

#method: The method used for the request, such as GET and POST.

  • headers: Header information of the request, in the form of Headers object or ByteString.

  • body: Requested body information: may be a Blob, BufferSource, FormData, URLSearchParams or USVString object. Note that GET or HEAD method requests cannot contain body information.

  • mode: Requested mode, such as cors, no-cors or same-origin.

  • credentials: Requested credentials, such as omit, same-origin or include.

  • cache: Requested cache mode: default, no-store, reload, no-cache, force-cache, or only-if-cached.

  • response

A Promise, when resolved returns the Response object:

Attributes:

status (number)

- HTTP request result parameter, in the range of 100–599
  • statusText (String)

    - Server Returned status report
  • ok (boolean)

    - true if 200 is returned indicating the request is successful
  • headers (Headers)

    -Return header information, detailed introduction below
  • url (String)

    -Requested address
  • Method:

text()

- Generate request text in the form of string
  • json()

    - Generate the result of
  • JSON.parse(responseText)
  • ##blob() - Generate a Blob

  • arrayBuffer() - Generate an ArrayBuffer

  • formData() - Generate formatted data , can be used for other requests

  • Other methods:

clone()

  • Response.error()

  • Response.redirect()

  • response.headers

  • has(name) (boolean) - Determine whether the information header exists

  • get(name) (String) - 获取信息头的数据

  • getAll(name) (Array) - 获取所有头部数据

  • set(name, value) - 设置信息头的参数

  • append(name, value) - 添加header的内容

  • delete(name) - 删除header的信息

  • forEach(function(value, name){ ... }, [thisContext]) - 循环读取header的信息

使用实例


//获取css里ul的id属性 
let uldom = document.getElementById("students"); 
//单独创建一个json文件,获取地址 
let url = "data.json"; 
 
function main(){ 
 fetch(url).then(respone=>{ 
 return respone.json(); 
 }).then(students=>{ 
 
 let html = ``; 
 for(let i=0, l=students.length; i<l; i++){ 
  let name = students[i].name; 
  let age = students[i].age; 
  html += ` 
  <li>姓名:${name},年龄:${age}</li> 
  ` 
 } 
 
 uldom.innerHTML = html; 
 }); 
} 
 
main();

结合await最终代码


let uldom = document.getElementById("students"); 
let url = "data.json"; 
 
async function main(){ 
 let respone = await fetch(url); 
 let students = await respone.json(); 
 
let html =``; 
for(let i=0, l=students.length; i<l; i++){ 
 let name = students[i].name; 
 let age = students[i].age; 
 html += ` 
 <li>姓名:${name},年龄:${age}</li> 
` 
} 
uldom.innerHTML = html; 
} 
main();

data.json文件内容如下:


[ 
 {"name":"张三","age":"3"}, 
 {"name":"李万","age":"1"}, 
 {"name":"王二","age":"4"}, 
 {"name":"二狗","age":"3"}, 
 {"name":"狗蛋","age":"5"}, 
 {"name":"牛娃","age":"7"} 
]

运行后结果是:


姓名:张三,年龄:3 
姓名:李万,年龄:1 
姓名:王二,年龄:4 
姓名:二狗,年龄:3 
姓名:狗蛋,年龄:5 
姓名:牛娃,年龄:7

The above is the detailed content of An example of how JavaScript uses fetch to complete asynchronous requests. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.