Understanding AsynchronyFirst of all, we have to understand that the request is an asynchronous process. Because the request takes time to send the request to the server and receive the request result. We have to wait for the request to complete and then execute the callback after the request is completed to process the received request results. fetch(url)For the convenience of learning, we borrow the API interface of the uni-app tutorial. const url = 'https://unidemo.dcloud.net.cn/api/news' We need to know that fetch is designed based on Promise. If you don’t understand it, it is recommended to learn es6 Promise first. fetch(url) can directly send a get request, and it is a Promise itself. Since it is a Promise, we can use the .then callback. Let’s try it. fetch(url).then(res => { console.log(res) }) What does it return? It is a response. Response is an encapsulated object that returns some request parameters. A more useful example is status, which tells you that the status code of the request is 200, indicating that the request was sent successfully. Now that we have sent a get request, what we are most concerned about is where the requested data is? response.json()Don't worry, click on the Prototype of Response and you will find a json method. Just tell you that this method also returns a Promise. Then we can return this promise for the next callback. In the next step, output the results to see what they are. fetch(url).then(response => { return response.json() }).then(res => { console.log(res) }) It turns out that the data we want is here. Combining async and awaitAlthough we can use fetch to execute callbacks to make requests above, the use of callbacks still makes the code less elegant. However, if you know the asynchronous-related keywords async and await, there are alternative ways of writing. After adding async to a function, the function becomes an asynchronous function, in which await can be used to make the code wait for the asynchronous operation Promise and return the callback result, which has the meaning of turning asynchrony into synchronization. const fetchAPI = async () => { const response = await fetch(url) const data = await response.json() console.log(data) } fetchAPI() Exception handlingAnd we can use the status code in the first step response to determine whether the next step can be carried out normally. const fetchAPI = async () => { const response = await fetch(url) if (response.status === 200) { const data = await response.json() console.log(data) }else{ console.log('Request exception') } } fetchAPI() Then, in order to consider some unexpected situations more rigorously, use try-catch to capture the exception. const fetchAPI = async () => { try { const response = await fetch(url) if (response.status === 200) { const data = await response.json() console.log(data) } else { console.log('Request exception') } } catch (err) { console.log(err) } } fetchAPI() post requestThe second input parameter of fetch is an object, which is the configuration parameters of the request. The request method can be set to post, and the request header and post input parameters can also be set. fetch(url, { method: "POST", headers: { 'Content-Type': 'application/json', ... }, body: JSON.stringify({ 'key': value, ... }) }) SummarizeThis is the end of this article about the use of js fetch asynchronous request. For more relevant content on the use of js fetch asynchronous request, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: docker cp copy files and enter the container
>>: Several methods to clear floating (recommended)
Table of contents 1. Overview 2. Use docker to de...
Table of contents What is an index? Leftmost pref...
If the developer uses Dockerfile to build the ima...
Preface When Ahhang was developing the Springboot...
In fact, it is not difficult to build an Apache c...
[Problem description] Our production environment ...
The difference between http and https is For some...
A brief analysis of rem First of all, rem is a CS...
The default storage directory of mysql is /var/li...
In the field of design, there are different desig...
To export MySQL query results to csv , you usuall...
HTML operation principle: 1. Local operation: ope...
1. Write the Dockerfile (1) Right-click the proje...
Share a real-time clock effect implemented with n...
How to allow remote connection in MySql To achiev...