Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use fetch to realize Asynchronous request in JavaScript

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to use fetch to achieve asynchronous request in JavaScript". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use fetch to achieve asynchronous request in JavaScript".

Ajax request

For a normal Ajax request, sending a json request with XHR usually 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 ()

How to implement it using fetch:

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

You can also use the async/await method.

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

With await, writing asynchronous code feels as good as synchronous code. Await can be followed by a Promise object, indicating that you wait for Promise resolve () to continue execution, and if Promise is reject () or throws an exception, it will be caught by the outside try...catch.

Use fetch

The main advantages of fetch are

Concise syntax, more semantic Promise implementation based on standards, and convenient support for async/await isomorphism

But it also has its shortcomings.

Fetch requests do not have cookie by default. You need to set fetch (url, {credentials: 'include'}) server to return an error code such as 400500 without reject. Only when the request cannot be completed due to network errors, fetch will be reject.

Fetch syntax:

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

Specific parameter case:

/ / compatibility package 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 resources to be acquired. This could be: a USVString string containing the URL to get the resource. A Request object.

Options (optional)

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

Method: the method used for the request, such as GET, POST.

Headers: the requested header information in the form of a Headers object or ByteString.

Body: the requested body information: it may be a Blob, BufferSource, FormData, URLSearchParams, or USVString object. Note that requests for GET or HEAD methods cannot contain body information.

Mode: the requested mode, such as cors, no-cors, or same-origin.

Credentials: the requested credentials, such as omit, same-origin, or include.

Cache: the requested cache mode: default, no-store, reload, no-cache, force-cache, or only-if-cached.

Response

When a Promise,resolve returns the Response object:

Attributes:

Status (number)-HTTP request result parameter, in the range of 100,599

StatusText (String)-status report returned by the server

Ok (boolean)-true if 200 indicates that the request is successful

Headers (Headers)-returns header information, described in more detail below

Url (String)-the requested address

Methods:

Text ()-generates the request text in the form of string

Json ()-generate the result of JSON.parse (responseText)

Blob ()-generate a Blob

ArrayBuffer ()-generate an ArrayBuffer

FormData ()-generates formatted data that can be used for other requests

Other methods:

Clone ()

Response.error ()

Response.redirect ()

Response.headers

Has (name) (boolean)-determines whether the header exists

Get (name) (String)-get the data of the header

GetAll (name) (Array)-get all header data

Set (name, value)-sets the parameters of the header

Append (name, value)-add the content of header

Delete (name)-deletes information from header

ForEach (function (value, name) {...}, [thisContext])-reads the information of header in a loop

Use an example

/ / get the id attribute let uldom = document.getElementById ("students") of ul in css; / / create a separate json file and get the address let url = "data.json"; function main () {fetch (url) .then (respone= > {return respone.json ();}) .then (students= > {let html = ``; for (let item0, students. Stories; I)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report