1. 程式人生 > 實用技巧 >Vue2020 - promise、fetch、axios、async/await、圖書館API介面案例

Vue2020 - promise、fetch、axios、async/await、圖書館API介面案例

Day4

目錄

介面呼叫方式

  • 原生ajax
  • 基於jQuery的ajax
  • fetch
  • axios

非同步

  • JavaScript的執行環境是「單執行緒」
  • 所謂單執行緒,是指JS引擎中負責解釋和執行JavaScript程式碼的執行緒只有一個,也就是一次只能完成一項任務,這個任務執行完後才能執行下一個,它會「阻塞」其他任務。這個任務可稱為主執行緒
  • 非同步模式可以一起執行多個任務
  • JS中常見的非同步呼叫
    • 定時任何
    • ajax
    • 事件函式

promise

  • 主要解決非同步深層巢狀的問題
  • promise 提供了簡潔的API 使得非同步操作更加容易
 
  <script type="text/javascript">
    /*
     1. Promise基本使用
           我們使用new來構建一個Promise  Promise的建構函式接收一個引數,是函式,並且傳入兩個引數:		   resolve,reject, 分別表示非同步操作執行成功後的回撥函式和非同步操作執行失敗後的回撥函式
    */


    var p = new Promise(function(resolve, reject){
      //2. 這裡用於實現非同步任務  setTimeout
      setTimeout(function(){
        var flag = false;
        if(flag) {
          //3. 正常情況
          resolve('hello');
        }else{
          //4. 異常情況
          reject('出錯了');
        }
      }, 100);
    });
    //  5 Promise例項生成以後,可以用then方法指定resolved狀態和reject狀態的回撥函式 
    //  在then方法中,你也可以直接return資料而不是Promise物件,在後面的then中就可以接收到資料了  
    p.then(function(data){
      console.log(data)
    },function(info){
      console.log(info)
    });
  </script>

基於Promise傳送Ajax請求

 
  <script type="text/javascript">
    /*
      基於Promise傳送Ajax請求
    */
    function queryData(url) {
     #   1.1 建立一個Promise例項
      var p = new Promise(function(resolve, reject){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
          if(xhr.readyState != 4) return;
          if(xhr.readyState == 4 && xhr.status == 200) {
            # 1.2 處理正常的情況
            resolve(xhr.responseText);
          }else{
            # 1.3 處理異常情況
            reject('伺服器錯誤');
          }
        };
        xhr.open('get', url);
        xhr.send(null);
      });
      return p;
    }
	# 注意:  這裡需要開啟一個服務 
    # 在then方法中,你也可以直接return資料而不是Promise物件,在後面的then中就可以接收到資料了
    queryData('http://localhost:3000/data')
      .then(function(data){
        console.log(data)
        #  1.4 想要繼續鏈式程式設計下去 需要 return  
        return queryData('http://localhost:3000/data1');
      })
      .then(function(data){
        console.log(data);
        return queryData('http://localhost:3000/data2');
      })
      .then(function(data){
        console.log(data)
      });
  </script>

Promise 基本API

例項方法

.then()
  • 得到非同步任務正確的結果
.catch()
  • 獲取異常資訊
.finally()
  • 成功與否都會執行(不是正式標準)
  
  <script type="text/javascript">
    /*
      Promise常用API-例項方法
    */
    // console.dir(Promise);
    function foo() {
      return new Promise(function(resolve, reject){
        setTimeout(function(){
          // resolve(123);
          reject('error');
        }, 100);
      })
    }
    // foo()
    //   .then(function(data){
    //     console.log(data)
    //   })
    //   .catch(function(data){
    //     console.log(data)
    //   })
    //   .finally(function(){
    //     console.log('finished')
    //   });

    // --------------------------
    // 兩種寫法是等效的
    foo()
      .then(function(data){
        # 得到非同步任務正確的結果
        console.log(data)
      },function(data){
        # 獲取異常資訊
        console.log(data)
      })
      # 成功與否都會執行(不是正式標準) 
      .finally(function(){
        console.log('finished')
      });
  </script>

靜態方法

.all()
  • Promise.all方法接受一個數組作引數,陣列中的物件(p1、p2、p3)均為promise例項(如果不是一個promise,該項會被用Promise.resolve轉換為一個promise)。它的狀態由這三個promise例項決定
.race()
  • Promise.race方法同樣接受一個數組作引數。當p1, p2, p3中有一個例項的狀態發生改變(變為fulfilledrejected),p的狀態就跟著改變。並把第一個改變狀態的promise的返回值,傳給p的回撥函式

  <script type="text/javascript">
    /*
      Promise常用API-物件方法
    */
    // console.dir(Promise)
    function queryData(url) {
      return new Promise(function(resolve, reject){
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
          if(xhr.readyState != 4) return;
          if(xhr.readyState == 4 && xhr.status == 200) {
            // 處理正常的情況
            resolve(xhr.responseText);
          }else{
            // 處理異常情況
            reject('伺服器錯誤');
          }
        };
        xhr.open('get', url);
        xhr.send(null);
      });
    }

    var p1 = queryData('http://localhost:3000/a1');
    var p2 = queryData('http://localhost:3000/a2');
    var p3 = queryData('http://localhost:3000/a3');
     Promise.all([p1,p2,p3]).then(function(result){
       //   all 中的引數  [p1,p2,p3]   和 返回的結果一 一對應["HELLO TOM", "HELLO JERRY", "HELLO SPIKE"]
       console.log(result) //["HELLO TOM", "HELLO JERRY", "HELLO SPIKE"]
     })
    Promise.race([p1,p2,p3]).then(function(result){
      // 由於p1執行較快,Promise的then()將獲得結果'P1'。p2,p3仍在繼續執行,但執行結果將被丟棄。
      console.log(result) // "HELLO TOM"
    })
  </script>

fetch

  • Fetch API是新的ajax解決方案 Fetch會返回Promise
  • fetch不是ajax的進一步封裝,而是原生js,沒有使用XMLHttpRequest物件
  • fetch(url, options).then()
  <script type="text/javascript">
    /*
      Fetch API 基本用法
      	fetch(url).then()
     	第一個引數請求的路徑   Fetch會返回Promise   所以我們可以使用then 拿到請求成功的結果 
    */
    fetch('http://localhost:3000/fdata').then(function(data){
      // text()方法屬於fetchAPI的一部分,它返回一個Promise例項物件,用於獲取後臺返回的資料
      return data.text();
    }).then(function(data){
      //   在這個then裡面我們能拿到最終的資料  
      console.log(data);
    })
  </script>

fetch API 中的 HTTP 請求

  • fetch(url, options).then()
  • HTTP協議,它給我們提供了很多的方法,如POST,GET,DELETE,UPDATE,PATCH和PUT
    • 預設的是 GET 請求
    • 需要在 options 物件中 指定對應的 method method:請求使用的方法
    • post 和 普通 請求的時候 需要在options 中 設定 請求頭 headers 和 body
   <script type="text/javascript">
        /*
              Fetch API 呼叫介面傳遞引數
        */
       #1.1 GET引數傳遞 - 傳統URL  通過url  ? 的形式傳參 
        fetch('http://localhost:3000/books?id=123', {
            	# get 請求可以省略不寫 預設的是GET 
                method: 'get'
            })
            .then(function(data) {
            	# 它返回一個Promise例項物件,用於獲取後臺返回的資料
                return data.text();
            }).then(function(data) {
            	# 在這個then裡面我們能拿到最終的資料  
                console.log(data)
            });

      #1.2  GET引數傳遞  restful形式的URL  通過/ 的形式傳遞引數  即  id = 456 和id後臺的配置有關   
        fetch('http://localhost:3000/books/456', {
            	# get 請求可以省略不寫 預設的是GET 
                method: 'get'
            })
            .then(function(data) {
                return data.text();
            }).then(function(data) {
                console.log(data)
            });

       #2.1  DELETE請求方式引數傳遞      刪除id  是  id=789
        fetch('http://localhost:3000/books/789', {
                method: 'delete'
            })
            .then(function(data) {
                return data.text();
            }).then(function(data) {
                console.log(data)
            });

       #3 POST請求傳參
        fetch('http://localhost:3000/books', {
                method: 'post',
            	# 3.1  傳遞資料 
                body: 'uname=lisi&pwd=123',
            	#  3.2  設定請求頭 
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            })
            .then(function(data) {
                return data.text();
            }).then(function(data) {
                console.log(data)
            });

       # POST請求傳參
        fetch('http://localhost:3000/books', {
                method: 'post',
                body: JSON.stringify({
                    uname: '張三',
                    pwd: '456'
                }),
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(function(data) {
                return data.text();
            }).then(function(data) {
                console.log(data)
            });

        # PUT請求傳參     修改id 是 123 的 
        fetch('http://localhost:3000/books/123', {
                method: 'put',
                body: JSON.stringify({
                    uname: '張三',
                    pwd: '789'
                }),
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(function(data) {
                return data.text();
            }).then(function(data) {
                console.log(data)
            });
    </script>

fetchAPI 中 響應格式

  • 用fetch來獲取資料,如果響應正常返回,我們首先看到的是一個response物件,其中包括返回的一堆原始位元組,這些位元組需要在收到後,需要我們通過呼叫方法將其轉換為相應格式的資料,比如JSONBLOB或者TEXT等等

    /*
      Fetch響應結果的資料格式
    */
    fetch('http://localhost:3000/json').then(function(data){
      // return data.json();   //  將獲取到的資料使用 json 轉換物件
      return data.text(); //  //  將獲取到的資料 轉換成字串 
    }).then(function(data){
      // console.log(data.uname)
      // console.log(typeof data)
      var obj = JSON.parse(data);
      console.log(obj.uname,obj.age,obj.gender)
    })

axios

  • 基於promise用於瀏覽器和node.js的http客戶端
  • 支援瀏覽器和node.js
  • 支援promise
  • 能攔截請求和響應
  • 自動轉換JSON資料
  • 能轉換請求和響應資料

axios基礎用法

  • get和 delete請求傳遞引數
    • 通過傳統的url 以 ? 的形式傳遞引數
    • restful 形式傳遞引數
    • 通過params 形式傳遞引數
  • post 和 put 請求傳遞引數
    • 通過選項傳遞引數
    • 通過 URLSearchParams 傳遞引數
    # 1. 傳送get 請求 
	axios.get('http://localhost:3000/adata').then(function(ret){ 
      #  拿到 ret 是一個物件      所有的物件都存在 ret 的data 屬性裡面
      // 注意data屬性是固定的用法,用於獲取後臺的實際資料
      // console.log(ret.data)
      console.log(ret)
    })
	# 2.  get 請求傳遞引數
    # 2.1  通過傳統的url  以 ? 的形式傳遞引數
	axios.get('http://localhost:3000/axios?id=123').then(function(ret){
      console.log(ret.data)
    })
    # 2.2  restful 形式傳遞引數 
    axios.get('http://localhost:3000/axios/123').then(function(ret){
      console.log(ret.data)
    })
	# 2.3  通過params  形式傳遞引數 
    axios.get('http://localhost:3000/axios', {
      params: {
        id: 789
      }
    }).then(function(ret){
      console.log(ret.data)
    })
	#3 axios delete 請求傳參     傳參的形式和 get 請求一樣
    axios.delete('http://localhost:3000/axios', {
      params: {
        id: 111
      }
    }).then(function(ret){
      console.log(ret.data)
    })

	# 4  axios 的 post 請求
    # 4.1  通過選項傳遞引數
    axios.post('http://localhost:3000/axios', {
      uname: 'lisi',
      pwd: 123
    }).then(function(ret){
      console.log(ret.data)
    })
	# 4.2  通過 URLSearchParams  傳遞引數 
    var params = new URLSearchParams();
    params.append('uname', 'zhangsan');
    params.append('pwd', '111');
    axios.post('http://localhost:3000/axios', params).then(function(ret){
      console.log(ret.data)
    })

 	#5  axios put 請求傳參   和 post 請求一樣 
    axios.put('http://localhost:3000/axios/123', {
      uname: 'lisi',
      pwd: 123
    }).then(function(ret){
      console.log(ret.data)
    })

axios 全域性配置

#  配置公共的請求頭 
axios.defaults.baseURL = 'https://api.example.com';
#  配置 超時時間
axios.defaults.timeout = 2500;
#  配置公共的請求頭
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
# 配置公共的 post 的 Content-Type
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';


axios 攔截器

  • 請求攔截器
    • 請求攔截器的作用是在請求傳送前進行一些操作
      • 例如在每個請求體里加上token,統一做了處理如果以後要改也非常容易
  • 響應攔截器
    • 響應攔截器的作用是在接收到響應後進行一些操作
      • 例如在伺服器返回登入狀態失效,需要重新登入的時候,跳轉到登入頁
	# 1. 請求攔截器 
	axios.interceptors.request.use(function(config) {
      console.log(config.url)
      # 1.1  任何請求都會經過這一步   在傳送請求之前做些什麼   
      config.headers.mytoken = 'nihao';
      # 1.2  這裡一定要return   否則配置不成功  
      return config;
    }, function(err){
       #1.3 對請求錯誤做點什麼    
      console.log(err)
    })
	#2. 響應攔截器 
    axios.interceptors.response.use(function(res) {
      #2.1  在接收響應做些什麼  
      var data = res.data;
      return data;
    }, function(err){
      #2.2 對響應錯誤做點什麼  
      console.log(err)
    })

async 和 await

  • async作為一個關鍵字放到函式前面
    • 任何一個async函式都會隱式返回一個promise
  • await關鍵字只能在使用async定義的函式中使用
    • ​ await後面可以直接跟一個 Promise例項物件
    • ​ await函式不能單獨使用
  • async/await 讓非同步程式碼看起來、表現起來更像同步程式碼
 	# 1.  async 基礎用法
    # 1.1 async作為一個關鍵字放到函式前面
	async function queryData() {
      # 1.2 await關鍵字只能在使用async定義的函式中使用      await後面可以直接跟一個 Promise例項物件
      var ret = await new Promise(function(resolve, reject){
        setTimeout(function(){
          resolve('nihao')
        },1000);
      })
      // console.log(ret.data)
      return ret;
    }
	# 1.3 任何一個async函式都會隱式返回一個promise   我們可以使用then 進行鏈式程式設計
    queryData().then(function(data){
      console.log(data)
    })

	#2.  async    函式處理多個非同步函式
    axios.defaults.baseURL = 'http://localhost:3000';

    async function queryData() {
      # 2.1  新增await之後 當前的await 返回結果之後才會執行後面的程式碼   
      
      var info = await axios.get('async1');
      #2.2  讓非同步程式碼看起來、表現起來更像同步程式碼
      var ret = await axios.get('async2?info=' + info.data);
      return ret.data;
    }

    queryData().then(function(data){
      console.log(data)
    })

圖書列表案例

1. 基於介面案例-獲取圖書列表

  • 匯入axios 用來發送ajax
  • 把獲取到的資料渲染到頁面上
  <div id="app">
        <div class="grid">
            <table>
                <thead>
                    <tr>
                        <th>編號</th>
                        <th>名稱</th>
                        <th>時間</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 5.  把books  中的資料渲染到頁面上   -->
                    <tr :key='item.id' v-for='item in books'>
                        <td>{{item.id}}</td>
                        <td>{{item.name}}</td>
                        <td>{{item.date }}</td>
                        <td>
                            <a href="">修改</a>
                            <span>|</span>
                            <a href="">刪除</a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    <script type="text/javascript" src="js/vue.js"></script>
	1.  匯入axios   
    <script type="text/javascript" src="js/axios.js"></script>
    <script type="text/javascript">
        /*
             圖書管理-新增圖書
         */
        # 2   配置公共的url地址  簡化後面的呼叫方式
        axios.defaults.baseURL = 'http://localhost:3000/';
        axios.interceptors.response.use(function(res) {
            return res.data;
        }, function(error) {
            console.log(error)
        });

        var vm = new Vue({
            el: '#app',
            data: {
                flag: false,
                submitFlag: false,
                id: '',
                name: '',
                books: []
            },
            methods: {
                # 3 定義一個方法 用來發送 ajax 
                # 3.1  使用 async  來 讓非同步的程式碼  以同步的形式書寫 
                queryData: async function() {
                    // 呼叫後臺介面獲取圖書列表資料
                    // var ret = await axios.get('books');
                    // this.books = ret.data;
					# 3.2  傳送ajax請求  把拿到的資料放在books 裡面   
                    this.books = await axios.get('books');
                }
            },

            mounted: function() {
				#  4 mounted  裡面 DOM已經載入完畢  在這裡呼叫函式  
                this.queryData();
            }
        });
    </script>

2 新增圖書

  • 獲取使用者輸入的資料 傳送到後臺
  • 渲染最新的資料到頁面上
 methods: {
    handle: async function(){
          if(this.flag) {
            // 編輯圖書
            // 就是根據當前的ID去更新陣列中對應的資料
            this.books.some((item) => {
              if(item.id == this.id) {
                item.name = this.name;
                // 完成更新操作之後,需要終止迴圈
                return true;
              }
            });
            this.flag = false;
          }else{
            # 1.1  在前面封裝好的 handle 方法中  傳送ajax請求  
            # 1.2  使用async  和 await 簡化操作 需要在 function 前面新增 async   
            var ret = await axios.post('books', {
              name: this.name
            })
            # 1.3  根據後臺返回的狀態碼判斷是否載入資料 
            if(ret.status == 200) {
             # 1.4  呼叫 queryData 這個方法  渲染最新的資料 
              this.queryData();
            }
          }
          // 清空表單
          this.id = '';
          this.name = '';
        },        
 }         

3 驗證圖書名稱是否存在

  • 新增圖書之前傳送請求驗證圖示是否已經存在
  • 如果不存在 往後臺裡面新增圖書名稱
    • 圖書存在與否只需要修改submitFlag的值即可
 watch: {
        name: async function(val) {
          // 驗證圖書名稱是否已經存在
          // var flag = this.books.some(function(item){
          //   return item.name == val;
          // });
          var ret = await axios.get('/books/book/' + this.name);
          if(ret.status == 1) {
            // 圖書名稱存在
            this.submitFlag = true;
          }else{
            // 圖書名稱不存在
            this.submitFlag = false;
          }
        }
},

4. 編輯圖書

  • 根據當前書的id 查詢需要編輯的書籍
  • 需要根據狀態位判斷是新增還是編輯
 methods: {
        handle: async function(){
          if(this.flag) {
            #4.3 編輯圖書   把使用者輸入的資訊提交到後臺
            var ret = await axios.put('books/' + this.id, {
              name: this.name
            });
            if(ret.status == 200){
              #4.4  完成新增後 重新載入列表資料
              this.queryData();
            }
            this.flag = false;
          }else{
            // 新增圖書
            var ret = await axios.post('books', {
              name: this.name
            })
            if(ret.status == 200) {
              // 重新載入列表資料
              this.queryData();
            }
          }
          // 清空表單
          this.id = '';
          this.name = '';
        },
        toEdit: async function(id){
          #4.1  flag狀態位用於區分編輯和新增操作
          this.flag = true;
          #4.2  根據id查詢出對應的圖書資訊  頁面中可以加載出來最新的資訊
          # 呼叫介面傳送ajax 請求  
          var ret = await axios.get('books/' + id);
          this.id = ret.id;
          this.name = ret.name;
        },

5 刪除圖書

  • 把需要刪除的id書籍 通過引數的形式傳遞到後臺
   deleteBook: async function(id){
          // 刪除圖書
          var ret = await axios.delete('books/' + id);
          if(ret.status == 200) {
            // 重新載入列表資料
            this.queryData();
          }
   }