Axios (XHR) and fetch

Time:2021-4-13

Axios (search arrow function)

import axios from "axios";
search = () => {
    axios.get(`https://api.github.com/search/users?q=${keyWord}`).then(
                response => {
                    console.log('successs');
                    console.log(response.data);
                },
                error => {
                    console.log('errors');
                    console.log(error);
                },
            );
}

fetch

search = () => {
        //Unoptimized version
        fetch(`https://api.github.com/search/users?q=${keyWord}`).then(
                    response => {
                        console.log('successs');
                        console.log(response);
                        //Continue to return a promise object
                        return response.json();
                    }
                ). then (response = > {// continue then
                    console.log('successs');
                    console.log(response.data.items);
                }). Catch (error = > {// unified processing error)
                    console.log('errors');
                    console.log(error);
                });
    }

//--- optimized version (asynchronous)
 search = async () => {
     try {
            //Note: the async identifier must be added to use await external functions
            const response = await fetch(`https://api.github.com/search/users?q=${keyWord}`);
            const data = await response.json();
            console.log('request success : ', data);
        } catch (error) {
            console.log('fetch error:', error);
        }
 }

Which is better?

This work adoptsCC agreementReprint must indicate the author and the link of this article

Recommended Today

Libp2p RS version 0.3.0 introduction

V0.3.0 released on 4.23, usingAsyncRead & AsyncWriteTo replace ourReadEx & WriteEx & SplitEx; SimplifiedKad/DHTImplementation logic. modify ReadEx & WriteEx & SplitEx: At first we tried to useasync-traitTo define their own IO operationsTraitFor more pure useasync/awaitTo write code. withReadExFor example, it is roughly as follows: #[async_trait] pub trait ReadEx { async fn read(&mut self, buf: &mut […]