使用promise封装ajax

直接上代码:服务器

function Ajax(method, url, data, progress = null) {
  return new Promise(function (resolve, reject) {
    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        try {//设置了超时时间, 防止因为该条件(即readystate等于4)成立, 进入该判断块, 下面的status读取不到, 致使抛出错误
          if (xhr.status >= 200 || xhr.status < 300 || xhr.status == 304) {
            resolve(xhr.responseText);
          } else {
            reject(new Error(xhr.statusText));
          } 
        } catch (error) {
          reject(new Error('服务器错误请重试'));
        }
      }
    }
相关文章
相关标签/搜索