小程序Promise 自封装请求函数

我封装在了app.js文件下,以便于其它页面js调用

/** 
   * 发起请求
   * @param r_url 请求地址
   * @param r_data 参数 {string/object/Array}
   * @param r_method 方法 默认为GET {GET、POST}
   * @param isLoad 是否显示加载框 默认不显示
   * @param r_dataType 响应数据 默认json
   */
  wxRequest: function (r_url, params = {}, r_method = 'GET', isLoad = true)
  {
    var _this = this;
    let promise = new Promise(function (resolve, reject) {
      if (isLoad === true) {
        wx.showLoading({ title: '正在获取' });
      }
      
      wx.request({
        url: _this.globalData.requestUrl + r_url,
        data: params,
        method: r_method,
        header: {
          "content-type": r_method == 'GET' ? 'application/json' : 'application/x-www-form-urlencoded'
        },
        timeout: 3000,
        success: function (res) {
          if (isLoad === true) {
            wx.hideLoading()
          }
          //请求成功
          resolve(res.data);
        },
        fail: function (err) {
          if (isLoad === true) {
            wx.hideLoading()
          }
          
          _this.showAlert('当前网络不佳');
          reject(err)
        }
      })
    })
    return promise;
  },

showAlert是我自己封装的一个弹窗(也在app.js),wx.showToast 改造的,代码如下

/**
   * 弹窗提示
   * @param {String} str 提示语句
   * @param icon  弹窗图标 默认为不显示 success、loading
   */
  showAlert: function (str = 'Msg', icon = 'none', durationTime = 1500)
  {
    var alert = wx.showToast({
      title: str,
      icon: icon,
      duration: durationTime,
      mask: true
    });
    return alert;
  },

调用:

// 获取应用实例
const app = getApp()

// 发起请求
app.wxRequest('/index/index').then(
    res => {
       // 获取接口参数
       console.log(res)
    }
)

不定期更新,喜欢就关注我吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值