超简单 Promise封装小程序ajax 超好用 以及封装登录

//网络类

//封装网络请求

const ajax = (ajaxData, method) => {
wx.showLoading({
title: '加载中',
mask: true
});
console.log('use ajax', ajaxData.url)
return new Promise((resolve, reject) => wx.request({
url: ajaxData.url,
method: method || 'GET',
data: ajaxData.data,
success(e) {
// console.log('ajax',e);
if (e.data.retcode == 0) {
resolve(e)
wx.hideLoading();
} else {
wx.showToast({
title:e.data.message,
icon:'none'
})
reject(e)
}
},
fail(e) {
wx.showLoading({
title: '网络错误'
})
}
}))
}

//判断是否登录
const checkLogin = () => {
return new Promise((resolve, reject) => {
let token = wx.getStorageSync('token');
let userId = wx.getStorageSync('userId');
//验证token是否存在
if (token && userId) {
//验证token是否过期
ajax({
url: API + 'account/checktoken',
data: {
userId,
token
}
}).then(e => {
//未过期 开始执行业务逻辑
resolve();
}).catch(e => {
// 过期 清空本地所有存储 返回到登录页面
if(e.data.retcode == 99){
wx.removeStorageSync('token');
wx.removeStorageSync('userId');
wx.reLaunch({
url: '../login/login'
})
}
})
} else {
// token 不存在 未登录过 返回到登录页面
// 执行清空 保证正确
wx.reLaunch({
url: '../login/login'
})
}
});
}

猜你喜欢

转载自www.cnblogs.com/likewpp/p/9456224.html
今日推荐