This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.

preface

There are many ways of asynchronous request, while fetch has the advantages of simplicity and JS native support. We do not need to introduce any additional packages to use in HTML, so it is very easy to use in daily learning and back-end test interface. This article introduces its usage, I believe you will be able to master.

Understanding the asynchronous


First we need to understand that requests are an asynchronous process.

Because requests require time to send the request to the server and receive the result of the request.

We have to wait for the request to complete and then perform the completed callback to process the result of the received request.

fetch(url)


For the sake of learning, let’s borrow the API from the UNI-App tutorial.

  const url = 'https://unidemo.dcloud.net.cn/api/news'
Copy the code

We need to know that fetch is designed based on Promise. If we do not know the recommendation, we should first learn es6 Promise: JS Promise and async/await usage in detail.

A FETCH (URL) can send a GET request directly and is itself a Promise.

So if it’s a Promise, then it’s ok. Then callback, let’s try that.

  fetch(url).then(res= > {
    console.log(res)
  })
Copy the code

What does it return? It’s a response.

Response is an encapsulated object that returns some of the parameters of the request.

A useful example is status, which tells you that the request’s status code is 200, indicating that the request was sent successfully.

Now that we’re sending a GET request, what we’re most concerned about is where is the data we’re getting?

response.json()


Hold on, click on the Response Prototype and you’ll see that there’s a JSON method.

It just tells you that this method also returns a Promise.

We can then return this promise for the next callback.

Print the result in the next step to see what it is.

  fetch(url).then(response= > {
    return response.json()
  }).then(res= > {
    console.log(res)
  })
Copy the code

It turns out that the data we’re going to get is right here.

Combine async and await


Above we can already use fetch to perform callbacks to make requests, but using callbacks is not very elegant.

But if you know the async-related keyword async and the await in it, there are alternatives.

After adding async to a function, it will become an asynchronous function, where you can use await to make the code wait for the asynchronous operation Promise and return the callback result, which has a hint of changing asynchrony to synchronization.

  const fetchAPI = async() = > {const response = await fetch(url)
    const data = await response.json()
    console.log(data)
  }

  fetchAPI()
Copy the code

Exception handling


And we can judge whether the next step can be carried out normally in the status code in the first step of response.

  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()
Copy the code

Then, for more serious consideration of unexpected conditions, we throw an exception to catch a try-catch.

  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()
Copy the code

A post request


The second input parameter of the fetch is an object, which is the configuration parameter of the request.

Request methods can set post, as well as request headers and post inputs.

  fetch(url, {
    method: "POST".headers: {
      'Content-Type': 'application/json'. },body: JSON.stringify({
      'key': value, ... })})Copy the code

Stern said

If you feel this article is helpful to you, welcome to click on the like collection oh, what mistakes or suggestions can also leave a message, thank you ~