App({
onLaunch: function () {
var openid=wx.getStorageSync('openid');
if(openid){
console.log('已经有openid的缓存了'+openid);
return;
}
console.log('没有openid的缓存 连接服务器获取中~');
wx.showLoading({
title: '',
mask:true
})
wx.login({
success(res) {
wx.request({
url: 'https://wxxcx.fun/openid.php',
data: {
code:res.code
},
success(res) {
wx.setStorageSync('openid',res.data);
console.log('获取openid的缓存成功'+wx.getStorageSync('openid'));
wx.hideLoading();
},
fail(res) {
//console.log('获取失败', res)
}
})
}
});
},
})
人为删除缓存后,第一次进页面就会报错,获取不到数据,需要刷新后才能正常。
因为其他会页面直接根据缓存中的openid加载数据内容,并不能等待app.js中的获得缓存的方法完成后再加载内容
网友回复
参考:
app.js
onLaunch:
wx.login({
success: async res => {
// 请求接口返回的user在这里赋值给 this.globalData.user
if (this.checkLoginReadyCallback) {
this.checkLoginReadyCallback(res);
}
},
fail: async res => {
if (this.checkLoginReadyCallback) {
this.checkLoginReadyCallback(res);
}
}
})
其它页面.js
onLoad:
const app = getApp()
if (app.globalData.user) {
// 请求其它接口
} else {
app.checkLoginReadyCallback = res => {
// 请求其它接口
}
}
JS异步,去了解一下。
在app.js里获取的openid可能滞后第一个加载的页面,因此在第一个加载的页面还需要判断是否有这个openid,如果没有还需要再请求服务器获得,然后再放缓存。