» » Using fetch for asynchronous requests in JavaScript


Using fetch for asynchronous requests in JavaScript

Author: bamboo06 on 1-04-2020, 19:14, views: 277

In the AJAX era, network requests such as APIs are made through XMLHttpRequest or encapsulated frameworks. The fetch framework now produced is simply to provide more powerful and efficient network requests. Although there are currently a few browser compatibility issues, when we make some asynchronous requests, we can use fetch to make perfect network requests.
Using fetch for asynchronous requests in JavaScript

Ajax request
For ordinary Ajax requests, sending a json request with XHR generally looks like this:
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = 'json';
xhr.onload = function(){
xhr.onerror = function(){

The way to use fetch:
    return response.json();

You can also use async / await:
    let response = await fetch(url);
    let data = await response.json();
} catch(e){

After using await, writing asynchronous code feels as cool as synchronous code. Await can be followed by a Promise object, which means that it will wait for the Promise resolve () to continue execution. If the Promise is rejected () or throws an exception, it will be caught by the outer try ... catch.

Use fetch
The main advantages of fetch are:
  • Concise syntax, more semantic
  • Convenient isomorphism
  • But it has its shortcomings

But it has its shortcomings:
  • fetch requests do not have cookies by default, you need to set fetch (url, {credentials: 'include'})
  • The server will not reject when it returns an error code of 400,500. Only when network errors cause the request to fail to complete, fetch will be rejected.

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

Specific parameter cases:
// Compatible 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
Define the resources to get. This could be: a USVString string containing the URL of the resource to be fetched. A Request object.
options (optional)
A configuration item object, including all the settings for the request. The optional parameters are:
method: The method used for the request, such as GET, POST.
headers: Requested header information, in the form of 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 include 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.

A Promise that returns a Response object when it resolves:

status (number)-HTTP request result parameter, in the range 100–599
statusText (String)-status report returned by the server
ok (boolean)-true if 200 is returned indicating the request was successful
headers (Headers)-return header information, detailed below
url (String)-the requested address

text ()-Generate request text as a string
json ()-Generate the result of JSON.parse (responseText)
blob ()-Generate a blob
arrayBuffer ()-Generate an ArrayBuffer
formData ()-Generate formatted data that can be used for other requests

Other methods:
clone ()
Response.error ()
Response.redirect ()
has (name) (boolean)-determine if the header exists
get (name) (String)-get the header data
getAll (name) (Array)-get all header data
set (name, value)-Set the parameters of the header
append (name, value)-add the contents of the header
delete (name)-delete header information
forEach (function (value, name) {...}, [thisContext])-loop through header information

// Get the id attribute of ul in css
let uldom = document.getElementById ("students");
// Create a json file separately and get the address
let url = "data.json";

function main () {
     fetch (url) .then (respone => {
         return respone.json ();
     }). then (students => {

         let html = ``;
         for (let i = 0, l = students.length; i <l; i ++) {
             let name = students [i] .name;
             let age = students [i] .age;
             html + = `
                 <li> Name: $ {name}, age: $ {age} </ li>

         uldom.innerHTML = html;

main ();

Combined with await final code
let uldom = document.getElementById("students");
let url = "data.json";

async function main(){
    let respone = await fetch(url);
    let students = await respone.json();

let html =``;
for(let i=0, l=students.length; i<l; i++){
    let name = students[i].name;
    let age = students[i].age;
    html += `
uldom.innerHTML = html;

The data.json file is as follows:

The result after running is:
Name: z1, age: 3
Name: z2, age: 1
Name: z3, age: 4
Name: z4, age: 3
Name: z5, age: 5 

Category: Javascript

Dear visitor, you are browsing our website as Guest.
We strongly recommend you to register and login to view hidden contents.
Comment on the news site is possible only within (days) days from the date of publication.