https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.getStorageSync.html
这个页面的两种获取方法都测试过,还是偶尔出现获取不到的情况
框架类型 | 问题类型 | API/组件名称 | 终端类型 | 微信版本 | 基础库版本 |
---|---|---|---|---|---|
小程序 | Bug | 数据缓存 | 微信iOS客户端 | 7.0.12 | 2.10.4 |
https://developers.weixin.qq.com/miniprogram/dev/api/storage/wx.getStorageSync.html
这个页面的两种获取方法都测试过,还是偶尔出现获取不到的情况
4 个回答
同步异步的问题 app.js getUserId: async function(data){ // 优先使用缓存数据 var cacheUid = wx.getStorageSync('userId') || this.globalData.userId || 0 if(cacheUid) { this.globalData.userId = cacheUid wx.setStorageSync('userId', cacheUid) return {code:200, userId:cacheUid, message:''} } // 缓存数据不存在,再请求接口,并缓存数据 var res = await util.request(api.GetUserId, data, 'POST') var uid = res.code == 200 ? res.data : 0 res.code != 200 && console.log('getUserId:', res.message); this.globalData.userId = uid wx.setStorageSync('userId', uid) return {code:res.code, userId:uid, message:res.message} } pages/test/test.js var app = getApp() onShow: async function() { var data = 'xxxxx' let {userId,message} = await app.getUserId(data) if (userId) { this.setData({ userId: userId, }) }else{ wx.showToast({ title:message, icon:'none', mask:true }) } }
若认为该回答有用,给回答者一个[ 有用 ]吧!!
这个很正常,2个本来就是异步执行的~
使用async/await~
或者用定时器轮询,什么时候有缓存了删除定时器~
这个有这种情况:
app.js里的请求还没返回时,show里面就去获取了。这个时候会失败
app.js里用await等待执行吧
app.js
util.request(api.GetUserId, data, 'POST').then(res => {
if (res.code == 200) {
this.globalData.userId = res.data
wx.setStorageSync('userId', res.data)
} else {
// util.showErrorToast(res.message);
}
})
pages/test/test.js
onShow: function() {
try {
let userId = wx.getStorageSync('userId')
if (userId) {
this.setData({
userId: userId,
})
}
} catch (e) {
// Do something when catch error
}