小程序網(wǎng)絡(luò)請求默認(rèn)為異步請求,在appjs的onLaunch運行后進行異步請求時,程序不會停止,Page頁已執(zhí)行onload, 我們希望onLaunch執(zhí)行完后再執(zhí)行onload。
//app.js
App({
onLaunch:function(){
????let self=this;
? ? wx.request({
url:'http://test.cn/login',//僅為示例,并非真實的接口地址
data: {},
success:function(res){
this.globalData.checkLogin =true;
//由于這里是網(wǎng)絡(luò)請求,可能會在 Page.onLoad 之后才返回
// 所以此處加入 callback 以防止這種情況
if(self.checkLoginReadyCallback){
self.checkLoginReadyCallback(res);
? ? ? ? }
? ? ? }
? ? })
? },
globalData: {
checkLogin:false
? }
})
//index.js
//獲取應(yīng)用實例
constapp = getApp()
Page({
data: {
test:false
? },
onLoad:function(){
letthat =this;
//判斷onLaunch是否執(zhí)行完畢
if(app.globalData.checkLogin){
? ? ? that.setData({
test:true
? ? ? })
}else{
app.checkLoginReadyCallback =res=>{
? ? ? ? that.setData({
test:true
? ? ? ? })
? ? ? };
? ? }
? }
})