zoukankan      html  css  js  c++  java
  • promise 封装 axios

    /*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;
    }

  • 相关阅读:
    [笔记] 辛普森积分
    Luogu P4175 [CTSC2008]网络管理
    Luogu P4331 [BOI2004]Sequence 数字序列
    Luogu P1456 Monkey King
    Luogu P3261 [JLOI2015]城池攻占
    Luogu P4309 [TJOI2013]最长上升子序列
    Luogu P4246 [SHOI2008]堵塞的交通
    Luogu P3638 [APIO2013]机器人
    Luogu P4294 [WC2008]游览计划
    CF613D Kingdom and its Cities
  • 原文地址:https://www.cnblogs.com/wangqi2019/p/10543395.html
Copyright © 2011-2022 走看看