前言:因为前端请求多数是异步请求,在一段代码中a代码还没成功b代码就已经执行完了,在项目中给我们带来了很大的坑,而且写过多的request看着也太乱,代码过多,不利于维护。
用到的技术点:wx.request()和Promise
promise:异步编程的解决方案(不太了解的自行百度学习下)
- 在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
}
- 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拉取地址:https://github.com/LingHuzh/Promise-wx.request.git
vue篇:vue使用promise封装axios
end~~~
如有错误或观点不一致的请评论留言共同讨论,本人前端小白一枚,根据自己实际项目遇到的问题进行总结分享,谢谢大家的阅读!