首页 > 移动平台 > 详细

promise 封装 axios

时间:2019-03-16 18:14:17      阅读:260      评论:0      收藏:0      [点我收藏+]

/*axios({
  method:"get",
  url:"./data.json",
  data:{
    id:10
  }
}).then((res)=>{
  console.log(res)
},(e)=>{
  console.log(e);
})*/

 

 

 

function axios(options) {
  let promise = new Promise((resolve, reject) => {  
    var xhr = new XMLHttpRequest();
    var data = "";
    //数据处理

    for (var key in options.data) {
    data += "&" + key + "=" + options.data[key]
    }

    if (options.method == "get") {

      let url = options.url + "?" + data.slice(1);
      xhr.open(options.method, url);
      xhr.send();
    } else if (options.method == "post") {

      xhr.open(options.method, options.url);
      xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
      xhr.send(data);
    }


    xhr.onreadystatechange = function () {
      let timer = null;
      let timeout = options.timeout?options.timeout:5000
      if(xhr.readyState == 4 && xhr.status == 200){
        let res = JSON.parse(xhr.responseText);
        clearTimeout(timer);
        resolve(res);
      }

     timer = setTimeout(()=>{
       clearTimeout(timer);
          reject(xhr.status);
        },timeout)

    }
  })
  return promise;
}

promise 封装 axios

原文:https://www.cnblogs.com/wangqi2019/p/10543395.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!