es6 promise ajax 请求实例运用代码

2018-09-10  本文已影响0人  sunxiaochuan

出处

2018前端面试总结,看完弄懂,工资少说加3K - 掘金 ---- es6 promise ajax

源码

const myHttpClient = url => {
  return new Promise((resolve, reject) => {
    let client = new XMLHttpRequest();
    client.open("GET", url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    client.setRequestHeader("Accept", "application/json");
    client.send();
    function handler() {
      if (this.readyState !== 4) {
        return;
      }
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText));
      }
    }
  });
};
使用
myHttpClient('https://www.baidu.com').then(res => {
  console.log(res);
}).catch(error => {
  console.log(error);
});

上一篇下一篇

猜你喜欢

热点阅读