前端小白不迷路 - 今天来利用promise简单封装axios函数发送Ajax请求

598 阅读2分钟

这是我参与8月更文挑战的第18天,活动详情查看:8月更文挑战

前言:

哈喽,大家晚上好啊,转眼都八月第18天了,坚持下去,希望就在前方,让我们继续更文的路途,前端小白不迷路 - 今天来利用promise简单封装axios函数发送Ajax请求。

封装一个Ajax请求,我们先搭建原生Ajax发送请求的结构:

 const xhr =new XMLHttpRequest()
      xhr.open('get','http://localhost:3000/get')  
      xhr.send(null)
      xhr.onreadystatechange=function(){
        if(xhr.readyState === 4){
          if(xhr.status === 200){
          console.log(xhr.responseText);
          }else{
           console.log(xhr.responseText)
          }
        }
      }

备注:请求地址是json-server提供的,大家可以去搜索json-server,利用npm全局安装json-server,然后利用它起一个服务,达到模拟后台数据的效果。

promise的结构搭建

先创建promise对象,然后使用该对象。promise对象里面放异步代码结构,所以把原生Ajax的代码段放到promise对象的回调函数中,成功的时候调用resolve函数,失败的时候调用reject函数,然后根据promise的状态决定走.then还是.catch。

    //创建promise实例对象p
    const p =new Promise((resolve,reject) =>{
      const xhr =new XMLHttpRequest()
      xhr.open('get','http://localhost:3000/get')
      xhr.send(null)
      xhr.onreadystatechange=function(){
        if(xhr.readyState === 4){
          if(xhr.status === 200){
        //成功的时候调用resolve函数
           resolve(xhr.responseText);
          }else{
        //失败的时候调用reject函数 
            reject(xhr.responseText)
          }
        }
      }
  })
 
// 使用promise对象
p.then(res =>{
  console.log(res);
}).catch(err =>{
  console.log(err);
})

利用promise封装简单的axios

封装的函数要想.then或者.catch,那么函数的返回值必须是一个promise对象,所以在函数内部之间return promise对象

<script>
  function axios(){
    //创建promise实例对象p
   return new Promise((resolve,reject) =>{
      const xhr =new XMLHttpRequest()
      xhr.open('get','http://localhost:3000/get')
      xhr.send(null)
      xhr.onreadystatechange=function(){
        if(xhr.readyState === 4){
          if(xhr.status === 200){
           resolve(xhr.responseText);
          }else{
            reject(xhr.responseText)
          }
        }
      }
  })
}
  axios().then(res =>{
    console.log(res);
  }).catch(err =>{
    console.log(err);
  })
</script>

最后一步:

因为我们封装代码是为了复用,函数体里把地址固定了,进一步优化函数,将地址和请求方式改为参数传递,更改后为:

<script>
  //形参是传个对象
  function axios(parameter){
   return new Promise((resolve,reject) =>{
      const xhr =new XMLHttpRequest()
      // 请求方式,请求地址
      xhr.open(parameter.method,parameter.url)
      xhr.send(null)
      xhr.onreadystatechange=function(){
        if(xhr.readyState === 4){
          if(xhr.status === 200){
           resolve(xhr.responseText);
          }else{
            reject(xhr.responseText)
          }
        }
      }
  })
}
  axios({
    method:'get',
    url:'http://localhost:3000/get'
    }).then(res =>{
    console.log(res);
  }).catch(err =>{
    console.log(err);
  })
</script>

形参传个对象,然后调用的时候传对象的属性,至此,axios的封装大功告成~~

后记

最近对promise研究比较深入,逐渐也入了迷。写到博客里是想总结一下,一方面是对知识点的巩固,另一方面是想给promise这块有困惑的伙伴提供一些帮助,如有错误,欢迎留言,以便改正。