axios(xhr) 和 fetch 兩種請求方式

frans發表於2020-12-31

axios (search箭頭函式)

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 = () => {
        //未優化版本
        fetch(`https://api.github.com/search/users?q=${keyWord}`).then(
                    response => {
                        console.log('successs');
                        console.log(response);
                        //繼續返回一個promise物件
                        return response.json();
                    }
                ).then(response => { //接下來繼續then
                    console.log('successs');
                    console.log(response.data.items);
                }).catch(error => { //統一處理error
                    console.log('errors');
                    console.log(error);
                });
    }

// ------------- 優化後版本(非同步)
 search = async () => {
     try {
            //注意: 使用 await  外部函式必須增加 async 標識
            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);
        }
 }

哪個更好呢?

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章