用promise手写ajax

es6之用promise手写ajax

首先promise的基本用法可以看上一篇 ES6之Promise对象

创建proimise

const getJson = function (url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onreadystatechange = function () {
      if (this.readyState === 4) {
        if (this.status === 200) {
          resolve(this.responseText, this)
        } else {
          const resJson = { code: this.status, response: this.response};
          reject(resJson);
        }
      } 
    };
    xhr.send();
  })
};

const postJSON = function(url, data) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    
    xhr.onreadystatechange = function () {
      if (this.readyState === 4) {
        if (this.status === 200) {
          resolve(JSON.parse(this.responseText), this);
        } else {
          const resJson = { code: this.status, response: this.response};
          reject(resJson)
        }
      } 
    };
    xhr.send(JSON.stringify(data))
  })
};

使用promise对象

getJSON('URL').then((res) => {
	console.log(res);
}).catch((err)=>{
	console.log(err);
})   

你可能感兴趣的:(es6,JavaScript)