Fetch

  1. Send request method classification

    1. xhr class: ajax (native xhr, troublesome), jQuery (third party, may generate callback hell), axios (third party)

    2. fetch: (built-in non-third-party, promise style)


  2. Features of fetch

    XMLHttpRequest does not conform to the separation of concerns (separation of concerns, that is, to split a complex thing). Official document

    fetch() splits the request sent by xhr into two steps. The first step is to contact the server, and the second step is to return data from the server.


  3. Fetch usage

    Full writing

    Simple usage (not optimized)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    //The first step: verify whether the server is in an active state and can establish a connection.
    fetch(url, options).then(function(response) {
    // Contacting the server was successful. response returns a server status object, which contains the header. (but no data is returned)
    return response.json //Return data, go to the next then() processing
    }, function(error) {
    // Failed to contact the server. The failure condition is very special: if the requested data server does not have it, the server will not be contacted to fail (but there will be 404 in the header);
    //If the entire browser is offline, the contact server failure will only be displayed
    return new Promise(()=>{}); //Interrupt the Promise chain
    }).then(
    response => {console.log('Get data successfully', response)},
    error => {console.log('Failed to get data', error)}
    )

    There is a json method (response.json) on the prototype object of the response response object, the return value is a promise instance, and the data is in this instance object. If the contact with the server is successful, the data acquisition is successful, the status of the instance is successful, and the successful data is saved in it; If the contact with the server is successful, Failed to obtain data, the status of the instance is failure, and the reason for the failure is stored in it.


    To get this data, it is best to use chained calls and process it in the next then().

    return new Promise(); is used to break the Promise chain. If you don’t write this code, there will be no return value when contacting the server fails, that is, it will return undefined by default, and then process it according to success; if this code is written to return an error, it will go to the next error branch in the promise chain, affecting the efficiency, it is better to interrupt.


    Code can be optimized with catch to handle errors uniformly. (preliminary optimization)

    1
    2
    3
    4
    5
    6
    7
    fetch(url, options).then(function(response) {
    return response.json
    }).then(
    response => {console.log('Get data successfully', response)},
    ).catch(
    error => {console.log(error);}
    )

  1. Use await async to optimize fetch code

    .then() can specify a success callback and a failure callback. But when .then() does not specify a failure callback (like the previous code), there is no need to write .then(), and it is more appropriate to use await async.


    await cannot be used directly, you need to add async to the function closest to await:

    1
    2
    3
    4
    5
    search = async() => {
    const response = await fetch(url, options) //wait for the successful result of fetch's promise instance: response
    const data = await response.json() //The second step is to get the data
    console. log(data);
    }

    await can only wait for a successful result, If you want to catch an exception, use try{} catch(){}. Code that might produce errors is written inside try{}:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    search = async() => {
    try {
    const response = await fetch(url, options)
    const data = await response.json()
    console. log(data);
    } catch(error){
    console.log('request error', error)
    }
    }

  1. fetch use case

    A case retrofit for React.4.2 with fetch. (when not using await async)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    fetch(`/api1/search/users2?q=${keyWord}`).then(
    response => {
    console.log('Contact the server successfully');
    return response.json();}
    ).then(response => {
    console.log('Get data successfully', response);
    PubSub. publish('My message', {isLoading: false, user: data. items})},
    ).catch(error => {
    PubSub. publish('My message', {isLoading: false, err: error. message})
    })

    When using await async

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    search = async() => {
    try {
    const response = await fetch(`/api1/search/users2?q=${keyWord}`)
    const data = await response.json()
    PubSub. publish('My message', {isLoading: false, user: data. items})
    } catch(error){
    console.log('request error', error);
    PubSub. publish('My message', {isLoading: false, err: error. message})
    }
    }

Share