Promise與Axios結合使用方法

html內使用 

    var p = new Promise(function(resolve, reject){
      setTimeout(function(){
        var flag = false;
        if(flag) {
          // 正常
          resolve('hello');
        }else{
          // 異常
          reject('出錯了');
        }
      }, 100);
    });
    //  Promise實例生成以後,可以用then方法指定resolved狀態和reject狀態的回調函數 
    //  在then方法中,你也可以直接return數據而不是Promise對象,在後面的then中就可以接收到數據了  
    p.then(function(data){
      console.log(data)
    },function(info){
      console.log(info)
    });

   /***********************************       *****************************************/

    send ajax
     /*
      基於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)
      });

    /*************************** async 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"
    })

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';

 # 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)
    })

axios OPTIONS操作

   # 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 async

# 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)
    })

收集總結而來,記錄

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章