小程序promise封装

小程序promise封装

// ajax promise封装
const requestFetch = (url, method, param) => {
  // 一个页面中可能会发送多个请求,ajaxTimes记载同时发送异步请求代码的次数,目的是为了在请求数据都完成后再消除加载框
  let ajaxTimes = 0;
  // const baseUrl = '基本url路径';

  ajaxTimes++;
  // 显示加载中效果
  wx.showLoading({
    title: "加载中",
    mask: true
  });
  let header = {
    // ...param.header,
    'Authorization': wx.getStorageSync('token'),
    'content-type': 'application/json' // 默认值
  };
  return new Promise((resolve, reject) => {
    wx.request({
      data: param,
      header: header,
      method: method,
      url: baseUrl + url,
      success: (result) => {
        const errArrCode = [2010, 1008, 2016]
        if (result.data.code == 2008) {
          Notify({
            type: 'danger',
            message: '登录失效,返回重新登录'
          });
          wx.removeStorageSync('token')
          setTimeout(() => {
            wx.reLaunch({
              url: '../login/login'
            })
          }, 1500)

        } else if (result.data.code == 2015) {
          Notify({
            type: 'danger',
            message: result.data.msg
          });
          wx.removeStorageSync('token')
          setTimeout(() => {
            wx.reLaunch({
              url: '../login/login'
            })
          }, 1500)
        } else if (errArrCode.includes(result.data.code)) {
          Notify({
            type: 'danger',
            message: result.data.msg
          });
          return
        } else if (result.data.code == 200) {
          resolve(result.data.data)
        } else {
          Notify({
            type: 'danger',
            message: '网络错误'
          });
        }
      },
      fail: (err) => {
        Notify({
          type: 'danger',
          message: '网络连接失败'
        });
        reject(err)
      },
      complete: () => {
        ajaxTimes--;
        // 关闭加载图标
        if (ajaxTimes === 0) {
          wx.hideLoading();
        }
      }
    })
  })
}

const deepCopy = (obj, cache = []) => {
  // typeof [] => 'object'
  // typeof {} => 'object'
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }
  // 如果传入的对象与缓存的相等, 则递归结束, 这样防止循环
  /**
   * 类似下面这种
   * var a = {b:1}
   * a.c = a
   */
  const hit = cache.filter(c => c.original === obj)[0];
  if (hit) {
    return hit.copy;
  }
  const copy = Array.isArray(obj) ? [] : {};
  // 将copy首先放入cache, 因为我们需要在递归deepCopy的时候引用它
  cache.push({
    original: obj,
    copy,
  });
  Object.keys(obj).forEach(key => {
    copy[key] = deepCopy(obj[key], cache);
  });
  return copy;
}
posted @ 2022-11-09 14:54  李帆同学  阅读(45)  评论(0编辑  收藏  举报
TOP