如何使用Promise实现一个优质的ajax请求?

18 min read

可以这样实现一个基本的ajax:

function ajax(url, method) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.onload = function() {
      if (this.status >= 200 && this.status < 300) {
        resolve(xhr.response);
      } else {
        reject({
          status: this.status,
          statusText: xhr.statusText
        });
      }
    };
    xhr.onerror = function() {
      reject({
        status: this.status,
        statusText: xhr.statusText
      });
    };
    xhr.send();
  });
}

使用示例:

ajax('https://jsonplaceholder.typicode.com/comments', 'GET')
  .then(function(response) {
    console.log(response);
  })
  .catch(function(error) {
    console.log(error);
  });