token在onLaunch中获取最为便利快速高效,但是在进入页面后调用接口时可能存在token还未获取到的情况,这时在每个落地页都加个token轮训有点不现实,那就在封装的request种进行token的判断及轮训并不阻塞接口的调用
封装request:
let requestMode=async function(params){
//此处校验token是否存在,若不存在轮训获取,存在啧继续执行
if(!app.token){
let state = await getAuthToken()
}
//此处继续执行request
return await new Promise((resolve, reject) => {
params.success = function(res) {
resolve(res)
}
params.fail = function(res) {
reject(res)
}
wx.request(params)
})
}
let loopTime=0
const getAuthToken=async function(){
try{
if(loopTime>50){
loopTime=0
throw({message:'请求超时'})
}
return await new Promise((resolve, reject)=>{
setTimeout(async function(){
try {
if(app.token){
resolve(app.token)
}else{
reject({ message: 'send' })
}
} catch (e) {
console.log(e)
throw (e)
}
loopTime++
},1000)
})
}catch(e){
if (e.message == 'send') {
return yield getAuthToken()
}else{
console.log("登录失败")
}
}
}