微信小程序使用promise封装wx.request()请求

前言:因为前端请求多数是异步请求,在一段代码中a代码还没成功b代码就已经执行完了,在项目中给我们带来了很大的坑,而且写过多的request看着也太乱,代码过多,不利于维护。


用到的技术点:wx.request()和Promise
promise:异步编程的解决方案(不太了解的自行百度学习下)


  1. 在util文件夹中创建.js文件写入以下代码
//先定义好公共的路径、header头
const baseUrl = 'https://test.ingclass.org';
const requestHeader = {  //header定义的都不一样,你们自行修改为你们所用的
	"content-type": 'application/json',
	"Authorization": 'Basic ' + base64.encode("7oewtwo8vnh7bq0wd6t4djy9" + ':' + "eq4vxysrhiwbme4ngk8ti7egm0mnyvas"),
	"tenant": 'MDAwMA==',
	"token": "Bearer " + wx.getStorageSync('token')
}

// 使用promise封装request
const api = {
  requestApi(url, method, data) {
    return new Promise(function (resolve, reject) {
      wx.request({
        url: baseUrl+ url,
        method: method,
        data: method === 'POST' ? JSON.stringify(data) : data,
        header: requestHeader,
        success(res) {
        resolve(res) //一定别忘了加成功之后resolve方法
          // 请求成功
          //这里是后端定义的code字段返回规则,你们按各自后端定义的字段规则修改
          if (res.data.code == 0) {
  			//请求成功
  			wx.hideLoading();
          } else if (res.data.code == 40001) { 
            wx.hideLoading();
            wx.navigateTo({
              url: '../index/index',
            })
          } else if (res.data.code == 40008) {
            //40008账号被挤掉
            wx.hideLoading();
          } else if (res.data.code == 40007) {
          	//token过期
            wx.hideLoading();
          } else {
            wx.hideLoading();
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        },
        fail(res) {
          reject(res) //失败之后reject方法
          wx.hideLoading()
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      })
    })
  }
}

//导出我们封装好的方法
module.exports = {
  api: api
}
  1. page页面调用
const util = require('../../utils/util.js')  //引入js文件

    util.api.requestApi(`/api/teacher/v1/api/screening/record/list/assignment/${ingPage}/10/2`, 'Get')
      .then(res => {
      //成功回调函数
        this.setData({
          num: res.data.data
        })
      })
      .catch(res => {
      //失败回调函数
        wx.hideLoading()
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          duration: 2000
        })
      })

附:封装好的git地址

git拉取地址:https://github.com/LingHuzh/Promise-wx.request.git


vue篇:vue使用promise封装axios


end~~~

如有错误或观点不一致的请评论留言共同讨论,本人前端小白一枚,根据自己实际项目遇到的问题进行总结分享,谢谢大家的阅读!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值