Vue Promise的axios请求封装详解

2019-11-16,,,,,

现在应该大部分公司都是前后端分离了。so,数据请求的封装还是必须的。

为了实现向ios中block封装请求的异步的效果,我采用JavaScript中promise这个对象。

 var p1 = New promise((resolve,reject)=>{
 var timeOut = Math.random() * 2;
  log('set timeout to: ' + timeOut + ' seconds.');
  setTimeout(function () {
    if (timeOut < 1) {
      log('call resolve()...');
      resolve('200 OK');
    }
    else {
      log('call reject()...');
      reject('timeout in ' + timeOut + ' seconds.');
    }
  }, timeOut * 1000);
})

其中resolve,reject就相当于是你定义了两个block,然后把数据传出去。

继续往下看,紧接着上面的代码

var p2 = p1.then(function (result) {  //resolve 导出的数据
  console.log('成功:' + result);
});
var p3 = p2.catch(function (reason) { //reject 导出的数据
  console.log('失败:' + reason);
});

通过查阅资料还发现另外两种用法,Promise.all 和 Promise.race这两种。

var p1 = new Promise(function (resolve, reject) {
  setTimeout(resolve, 500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
  setTimeout(resolve, 600, 'P2');
});
// 同时执行p1和p2,并在它们都完成后执行then:
Promise.all([p1, p2]).then(function (results) {
  console.log(results); // 获得一个Array: ['P1', 'P2']
});

这一种是p1 和 p2 都返回了数据,才会执行all后面的then函数。挺像ios中GCD的notify函数

第二种

var p1 = new Promise(function (resolve, reject) {
  setTimeout(resolve, 500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
  setTimeout(resolve, 600, 'P2');
});
Promise.race([p1, p2]).then(function (result) {
  console.log(result); // 'P1'
});

race跑步的意思,看谁跑得快,跑得慢的就被摒弃掉了。

上面这些是封装的基础,下面来看具体应用#

基于axios的请求封装

//判断请求环境来区分链接 生产环境和测试环境
const ajaxUrl = env === 'development' ? 
  'https://www.baidu.com' :
  env === 'production' ?
  'https://www.baidu.com' :
  'https://www.baidu.com';

util.ajax = axios.create({
  baseURL: ajaxUrl,
  timeout: 30000
});
// options中包含着数据
export function axiosfetch(options) {
  
  return new Promise((resolve, reject) => {
    var token = window.localStorage.getItem('token') ? window.localStorage.getItem('token') : "";
    var cid = window.localStorage.getItem('X-CID') ? window.localStorage.getItem('X-CID') : "";
    // var language = window.localStorage.getItem('language') ? window.localStorage.getItem('language') : "";
    
    var language = tools.getCookie('language')?tools.getCookie('language'): navigator.language;
    language = language == "en-US" ? "en" : language ;
    debug.log(language)
    var params = tools.deepClone(options.params);//深拷贝
    var sign_str = tools.sign(params); //签名
    const instance = axios.create({
      baseURL: ajaxUrl,
      timeout: 30000,
      //instance创建一个axios实例,可以自定义配置,可在 axios文档中查看详情
      //所有的请求都会带上这些配置,比如全局都要用的身份信息等。
      headers: { //所需的信息放到header头中
        // 'Content-Type': 'application/json',
        "Authorization": token,
        "X-CID":cid,
        "X-LOCALE":language,
        "X-SIGN":sign_str
      },
      // timeout: 30 * 1000 //30秒超时
    });
    
    let httpDefaultOpts = { //http默认配置
      method:options.method,
      url: options.url,
      timeout: 600000,
      params:Object.assign(params),
      data:qs.stringify(Object.assign(params)),
      // headers: options.method=='get'?{
      //   'X-Requested-With': 'XMLHttpRequest',
      //   "Accept": "application/json",
      //   "Content-Type": "application/json; charset=UTF-8",
      //   "Authorization": token
      // }:{
      //   'X-Requested-With': 'XMLHttpRequest',
      //   'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
      //   "Authorization": token
      // }
    }

    if(options.method=='get'){ //判断是get请求还是post请求
      delete httpDefaultOpts.data
    }else{
      delete httpDefaultOpts.params
    }
    instance(httpDefaultOpts)
      .then(response => {//then 请求成功之后进行什么操作
        debug.log('参数:')
        debug.log(options.params)
        debug.log('响应:')
        debug.log(response)
        debug.log(response.data.errno)
        if(response.data.errno == 401){
          // alert(response.data.errmsg)
          // window.location.href = window.location.protocol + "//" +window.location.host + '/#/login'
          return
        }
        if(response.data.errno == 400){
          reject(response)
          return
        }
        resolve(response)//把请求到的数据发到引用请求的地方
      })
      .catch(error => {
        // console.log('请求异常信息=>:' + options.params + '\n' + '响应' + error)
        debug.log('请求异常信息=>:' + options.params + '\n' + '响应' + error)
        reject(error)
      })
  })
}

外面再包一层

export function getNodeDetailInfo(address) {
  return axiosfetch({
    url:api.nodeDetailAPI,//链接
    method:"get",//get请求
    params:{//数据
      address:address
    }
  })
}

再下面就是实际应用。

   getNodeDetailInfo(address).then(res => {
          var data = res.data.data;
        }).catch(error => {
          console.log(error, '请求失败')
        })

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持北冥有鱼。

您可能感兴趣的文章:

  • vue中Axios的封装与API接口的管理详解
  • 详解Vue 2.0封装axios笔记
  • vue 里面使用axios 和封装的示例代码
  • 浅谈在Vue-cli里基于axios封装复用请求
  • vue 2.x 中axios 封装的get 和post方法
  • vue2.0学习之axios的封装与vuex介绍
  • Vue二次封装axios为插件使用详解
  • vue axios 二次封装的示例代码
  • 详解vue axios二次封装
  • 关于Vue中axios的封装实例详解

《Vue Promise的axios请求封装详解.doc》

下载本文的Word格式文档,以方便收藏与打印。