基于Promise async实例封装fetch Apis实例

124 阅读2分钟

在看实例之前我们首先明确三个es6中的概念。

  • Promise 是异步编程的一种解决方案,其实是一个构造函数,自己身上有all、reject、resolve这几个方法,原型上有then、catch等方法。
  • async和await是es7中提出来的更加优雅的一种异步编程解决方案。
  • Fetch API提供了一个 JavaScript接口,用于访问和操纵HTTP管道的部分,例如请求和响应。它还提供了一个全局 fetch()方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。

下面是app.js调用封装好的接口

const http = new EasyHttp;

// get请求数据
http.get("http://jsonplaceholder.typicode.com/users")
       .then((data) => {
         console.log(data);
       })
      .catch(err => console.log(err))

// 传输数据
// const data = {
//   name:"Henry",
//   username:"米斯特吴",
//   email:"27732357@qq.com"
// };

// post user
// http.post("http://jsonplaceholder.typicode.com/users",data)
//     .then(data => console.log(data))
//     .catch(err => console.log(err));

// update user
// http.put("http://jsonplaceholder.typicode.com/users/2",data)
//     .then(data => console.log(data))
//     .catch(err => console.log(err));

// delete user
// http.delete('http://jsonplaceholder.typicode.com/users/2')
 //    .then(data => console.log(data))
 //    .catch(err => console.log(err));

下面是基于promise封装的easyhttp.js

/**
 * 封装fetch
 * 更快,更简单的请求数据
 *
 * @version 1.0.0
 * @author  米斯特吴
 * @license MIT
 *
 **/

 class EasyHttp{
   // get 
   get(url){
     return new Promise((resolve,reject) => {
        fetch(url)
          .then(res => res.json())
          .then(data => resolve(data))
          .catch(err => reject(err))
     })
   }

   // post
   post(url,data){
    return new Promise((resolve,reject) => {
       fetch(url,{
         method:"POST",
         headers:{
           'Content-type':'application/json'
         },
         body:JSON.stringify(data)
       })
         .then(res => res.json())
         .then(data => resolve(data))
         .catch(err => reject(err))
    })
  }

  // put
  put(url,data){
    return new Promise((resolve,reject) => {
       fetch(url,{
         method:"PUT",
         headers:{
           'Content-type':'application/json'
         },
         body:JSON.stringify(data)
       })
         .then(res => res.json())
         .then(data => resolve(data))
         .catch(err => reject(err))
    })
  }

  // delete
  delete(url){
    return new Promise((resolve,reject) => {
       fetch(url,{
         method:"DELETE",
         headers:{
           'Content-type':'application/json'
         }
       })
         .then(res => res.json())
         .then(data => resolve('数据删除成功!'))
         .catch(err => reject(err))
    })
  }
 }

下面是基于async和await封装的easyhttp.js2.0版本

/**
 * 封装fetch
 * 更快,更简单的请求数据
 *
 * @version 2.0.0
 * @author  米斯特吴
 * @license MIT
 *
 **/

 class EasyHttp{
   // get 
   async get(url){
     const response = await fetch(url);
     const resData = await response.json();
     return resData;
   }

   // post
   async post(url,data){
      const response = await fetch(url,{
         method:"POST",
         headers:{
           'Content-type':'application/json'
         },
         body:JSON.stringify(data)
       });
      const resData = await response.json();
      return resData;
  }

  // put
  async put(url,data){
      const response = await fetch(url,{
         method:"PUT",
         headers:{
           'Content-type':'application/json'
         },
         body:JSON.stringify(data)
       });

       const resData = await response.json();
       return resData;    
  }

  // delete
  async delete(url){
      const response = await fetch(url,{
        method:"DELETE",
        headers:{
          'Content-type':'application/json'
        }
      })
      const resData = await "数据删除成功!";
      return resData;
  }
 }