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

Understand the implementation of Nginx location matching in one article

Since the team is separating the front-end and ba...

Uncommon but useful tags in Xhtml

Xhtml has many tags that are not commonly used but...

XHTML introductory tutorial: Use of list tags

Lists are used to list a series of similar or rela...

IE8 Beta 1 has two areas that require your attention

<br />Related articles: Web skills: Multiple...

CSS to achieve Skeleton Screen effect

When loading network data, in order to improve th...

How to Easily Remove Source Installed Packages in Linux

Step 1: Install Stow In this example, we are usin...

Write a React-like framework from scratch

Recently I saw the article Build your own React o...

Several methods of calling js in a are sorted out and recommended for use

We often use click events in the a tag: 1. a href=...

Tutorial on installing MySQL under Linux

Table of contents 1. Delete the old version 2. Ch...

Using MySQL in Windows: Implementing Automatic Scheduled Backups

1. Write a backup script rem auther:www.yumi-info...

A tutorial on how to install, use, and automatically compile TypeScript

1. Introduction to TypeScript The previous articl...