Detailed example of using js fetch asynchronous request

Detailed example of using js fetch asynchronous request

Understanding Asynchrony

First 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 await

Although 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 handling

And 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 request

The 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,
      ...
    })
  })

Summarize

This 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:
  • JavaScript uses fetch to implement asynchronous request method example

<<:  docker cp copy files and enter the container

>>:  Several methods to clear floating (recommended)

Recommend

Use docker to deploy tomcat and connect to skywalking

Table of contents 1. Overview 2. Use docker to de...

How to design and optimize MySQL indexes

Table of contents What is an index? Leftmost pref...

Docker data volume common operation code examples

If the developer uses Dockerfile to build the ima...

Modification of time zone problem of MySQL container in Docker

Preface When Ahhang was developing the Springboot...

Analysis of the process of building a cluster environment with Apache and Tomcat

In fact, it is not difficult to build an Apache c...

Detailed analysis of MySQL instance crash cases

[Problem description] Our production environment ...

Complete steps to upgrade Nginx http to https

The difference between http and https is For some...

Example of how to adapt the Vue project to the large screen

A brief analysis of rem First of all, rem is a CS...

Implementation of mysql8.0.11 data directory migration

The default storage directory of mysql is /var/li...

7 cool dynamic website designs for inspiration

In the field of design, there are different desig...

How to export mysql query results to csv

To export MySQL query results to csv , you usuall...

Basic structure of HTML documents (basic knowledge of making web pages)

HTML operation principle: 1. Local operation: ope...

Native JS to implement real-time clock

Share a real-time clock effect implemented with n...

How to allow remote connection in MySql

How to allow remote connection in MySql To achiev...