Vue第四天異步調(diào)用Promise&&axios

接口調(diào)用方式

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

異步

  • JavaScript的執(zhí)行環(huán)境是「單線程」
  • 所謂單線程,是指JS引擎中負(fù)責(zé)解釋和執(zhí)行JavaScript代碼的線程只有一個,也就是一次只能完成一項任務(wù),這個任務(wù)執(zhí)行完后才能執(zhí)行下一個,它會「阻塞」其他任務(wù)。這個任務(wù)可稱為主線程
  • 異步模式可以一起執(zhí)行多個任務(wù)
  • JS中常見的異步調(diào)用
    • 定時任何
    • ajax
    • 事件函數(shù)

promise

Pomise是異步編程的一種解決方法,從語法上講它是一個對象,從它可以獲取異步操作的消息

  • 主要解決異步深層嵌套的問題
  • promise 提供了簡潔的API 使得異步操作更加容易

promise基本用法

  • 我們使用new來構(gòu)建一個Promise Promise的構(gòu)造函數(shù)接收一個參數(shù),是函數(shù),并且傳入兩個參數(shù):
  • resolve,reject, 分別表示異步操作執(zhí)行成功后的回調(diào)函數(shù)和異步操作執(zhí)行失敗后的回調(diào)函數(shù),并通過p.then獲取處理結(jié)果
var p = new Promise(function(resolve, reject){
      // 這里用于實現(xiàn)異步任務(wù)
      setTimeout(function(){
        var flag = false;
        if(flag) {
          // 正常情況
          resolve('hello');
        }else{
          // 異常情況
          reject('出錯了');
        }
      }, 100);
    });
    p.then(function(data){
      console.log(data)//hello
    },function(info){
      console.log(info)//出錯了
    });


  /*
      基于Promise發(fā)送Ajax請求
    */
    function queryData(url) {
      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) {
            // 處理正常的情況
            resolve(xhr.responseText);
          }else{
            // 處理異常情況
            reject('服務(wù)器錯誤');
          }
        };
        xhr.open('get', url);
        xhr.send(null);
      });
      return p;
    }

 // 發(fā)送多個ajax請求并且保證順序
    queryData('http://localhost:3000/data')
      .then(function(data){
        console.log(data)
        return queryData('http://localhost:3000/data1');
      })
      .then(function(data){
        console.log(data);
        return queryData('http://localhost:3000/data2');
      })
      .then(function(data){
        console.log(data)
      });

then參數(shù)中的返回值

1、返回Promise實例對象

  • 返回一個該實例對象會調(diào)用下一個then
    2、返回普通值
  • 返回的普通值會傳遞給下一個then,通過then參數(shù)中的參數(shù)接收該值
/*
      then參數(shù)中的函數(shù)返回值
    */
    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('服務(wù)器錯誤');
          }
        };
        xhr.open('get', url);
        xhr.send(null);
      });
    }
    queryData('http://localhost:3000/data')
      .then(function(data){
        return queryData('http://localhost:3000/data1');
      })
      .then(function(data){
        return new Promise(function(resolve, reject){
          setTimeout(function(){
            resolve(123);
          },1000)
        });
      })
      .then(function(data){
        return 'hello';
      })
      .then(function(data){
        console.log(data)//hello
      })

Promise常用的API

  • 實例方法
    .then()

  • 得到異步任務(wù)正確的結(jié)果

.catch()

  • 獲取異常信息

.finally()

  • 成功與否都會執(zhí)行(不是正式標(biāo)準(zhǔn))
 /*
      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')
      });

.all()

  • Promise.all方法接受一個數(shù)組作參數(shù),數(shù)組中的對象(p1、p2、p3)均為promise實例(如果不是一個promise,該項會被用Promise.resolve轉(zhuǎn)換為一個promise)。它的狀態(tài)由這三個promise實例決定
    .race()
  • Promise.race方法同樣接受一個數(shù)組作參數(shù)。當(dāng)p1, p2, p3中有一個實例的狀態(tài)發(fā)生改變(變?yōu)閒ulfilled或rejected),p的狀態(tài)就跟著改變。并把第一個改變狀態(tài)的promise的返回值,傳給p的回調(diào)函數(shù)
  /*
      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('服務(wù)器錯誤');
            }
          };
          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) {
      //        console.log(result)
      //    })
      //    .catch(err => {
      //        console.log('err: ', err)
      //    })

      // Promise.allSettled([p1, p2, p3])
      //    .then(function (result) {
      //        console.log(result)
      //    })
      //    .catch(err => {
      //        console.log('err: ', err)
      //    })
      Promise.race([p1, p2, p3]).then(function (result) {
        console.log(result);
      });

fetch

  • Fetch API是新的ajax解決方案 Fetch會返回Promise
  • fetch不是ajax的進(jìn)一步封裝,而是原生js,沒有使用XMLHttpRequest對象。
  • fetch(url, options).then()
  /*
      Fetch API 基本用法
    */
      fetch('http://localhost:3000/fdata')
        .then(function (data) {
          // text()方法屬于fetchAPI的一部分,它返回一個Promise實例對象,用于獲取后臺返回的數(shù)據(jù)
          return data.text();
        })
        .then(function (data) {
          console.log(data);
        });

fetch請求參數(shù)

常見的配置選項

  • method(string):HTTP請求。默認(rèn)方法為GET(GET,DELETE,UPDATE,PATCH和PUT)
  • 默認(rèn)的是 GET 請求
  • 需要在 options 對象中 指定對應(yīng)的 method method:請求使用的方法
  • post 和 普通 請求的時候 需要在options 中 設(shè)置 請求頭 headers 和 body
  • body(string):HTTP的請求參數(shù)
  • headers(Object):HTTP的請求頭,默認(rèn)為{}
     /*
              Fetch API 調(diào)用接口傳遞參數(shù)
        */
       #1.1 GET參數(shù)傳遞 - 傳統(tǒng)URL  通過url  ? 的形式傳參 
        fetch('http://localhost:3000/books?id=123', {
                # get 請求可以省略不寫 默認(rèn)的是GET 
                method: 'get'
            })
            .then(function(data) {
                # 它返回一個Promise實例對象,用于獲取后臺返回的數(shù)據(jù)
                return data.text();
            }).then(function(data) {
                # 在這個then里面我們能拿到最終的數(shù)據(jù)  
                console.log(data)
            });

      #1.2  GET參數(shù)傳遞  restful形式的URL  通過/ 的形式傳遞參數(shù)  即  id = 456 和id后臺的配置有關(guān)   
        fetch('http://localhost:3000/books/456', {
                # get 請求可以省略不寫 默認(rèn)的是GET 
                method: 'get'
            })
            .then(function(data) {
                return data.text();
            }).then(function(data) {
                console.log(data)
            });

       #2.1  DELETE請求方式參數(shù)傳遞      刪除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  傳遞數(shù)據(jù) 
                body: 'uname=lisi&pwd=123',
                #  3.2  設(shè)置請求頭 
                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)
            });

fetchAPI 中 響應(yīng)格式

用fetch來獲取數(shù)據(jù),如果響應(yīng)正常返回,我們首先看到的是一個response對象,其中包括返回的一堆原始字節(jié),這些字節(jié)需要在收到后,需要我們通過調(diào)用方法將其轉(zhuǎn)換為相應(yīng)格式的數(shù)據(jù),比如JSON,BLOB或者TEXT等等

  • text():將返回體處理成字符串類型
  • json(): 返回結(jié)果和JSON.parse(responseText)一樣
/*
      Fetch響應(yīng)結(jié)果的數(shù)據(jù)格式
    */
      fetch('http://localhost:3000/json')
        .then(function (data) {
          // return data.json();//  將獲取到的數(shù)據(jù)使用 json 轉(zhuǎn)換對象
          return data.text();//  將獲取到的數(shù)據(jù) 轉(zhuǎn)換成字符串 
        })
        .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
  • 能攔截請求和響應(yīng)
  • 自動轉(zhuǎn)換JSON數(shù)據(jù)
  • 能轉(zhuǎn)換請求和響應(yīng)數(shù)據(jù)

axios基礎(chǔ)用法

  • get和 delete請求傳遞參數(shù)
    • 通過傳統(tǒng)的url 以 ? 的形式傳遞參數(shù)
    • restful 形式傳遞參數(shù)
    • 通過params 形式傳遞參數(shù)
  • post 和 put 請求傳遞參數(shù)
    • 通過選項傳遞參數(shù)
    • 通過 URLSearchParams 傳遞參數(shù)
 # 1. 發(fā)送get 請求 
    axios.get('http://localhost:3000/adata').then(function(ret){ 
      #  拿到 ret 是一個對象      所有的對象都存在 ret 的data 屬性里面
      // 注意data屬性是固定的用法,用于獲取后臺的實際數(shù)據(jù)
      // console.log(ret.data)
      console.log(ret)
    })
# 2.  get 請求傳遞參數(shù)
    # 2.1  通過傳統(tǒng)的url  以 ? 的形式傳遞參數(shù)
    axios.get('http://localhost:3000/axios?id=123').then(function(ret){
      console.log(ret.data)
    })
    # 2.2  restful 形式傳遞參數(shù) 
    axios.get('http://localhost:3000/axios/123').then(function(ret){
      console.log(ret.data)
    })
    # 2.3  通過params  形式傳遞參數(shù) 
    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  通過選項傳遞參數(shù)
    axios.post('http://localhost:3000/axios', {
      uname: 'lisi',
      pwd: 123
    }).then(function(ret){
      console.log(ret.data)
    })
 # 4.2  通過 URLSearchParams  傳遞參數(shù) 
    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 全局配置

相應(yīng)結(jié)果的主要屬性:

  • data:實際響應(yīng)回來的數(shù)據(jù)
  • headers:響應(yīng)頭信息
  • status:響應(yīng)狀態(tài)碼
  • statusText:相應(yīng)狀態(tài)信息
#  配置公共的請求頭 
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 攔截器

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

async 和 await

  • async作為一個關(guān)鍵字放到函數(shù)前面
    • 任何一個async函數(shù)都會隱式返回一個promise
  • await關(guān)鍵字只能在使用async定義的函數(shù)中使用
    • await后面可以直接跟一個 Promise實例對象
    • await函數(shù)不能單獨使用
 /*
      async/await 處理異步操作:
      async函數(shù)返回一個Promise實例對象
      await后面可以直接跟一個 Promise實例對象
    */
      axios.defaults.baseURL = 'http:localhost:3000';
      // axios.get('adata').then(function(ret){
      //   console.log(ret.data)
      // })

      // async function queryData() {
      //   var ret = await axios.get('adata');
      //   // console.log(ret.data)
      //   return ret.data;
      // }

      async function queryData() {
        try {
          var ret = await new Promise(function (resolve, reject) {
            setTimeout(function () {
              // resolve('nihao')
              reject('error');
            }, 1000);
          });
          console.log(ret);
          return ret;
        } catch (err) {
          console.log('----err: ', err);
        }
      }

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

async/await 讓異步代碼看起來、表現(xiàn)起來更像同步代碼

#2.  async    函數(shù)處理多個異步函數(shù)
    axios.defaults.baseURL = 'http://localhost:3000';

    async function queryData() {
      # 2.1  添加await之后 當(dāng)前的await 返回結(jié)果之后才會執(zhí)行后面的代碼   
      
      var info = await axios.get('async1');
      #2.2  讓異步代碼看起來、表現(xiàn)起來更像同步代碼
      var ret = await axios.get('async2?info=' + info.data);
      return ret.data;
    }

    queryData().then(function(data){
      console.log(data)
    })
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容