Originally, according to the event sequence, when the applet is initialized, the onLaunch in the App will be triggered, and then the onLoad in the Page will be executed. However, the onLoad event in the Page has already been executed when the onLaunch request is obtained and the return value is waiting.

//app.js App({ onLaunch: function () { console.log('onLaunch'); Wx. request({url: 'test.php', // only for example) data: {}, success: function(res) { console.log('onLaunch-request-success'); EmployId = res.employID; // Assign a value to the global variable for the page to judge. } }) }, globalData: { employId: '' } })Copy the code
Const app = getApp() Page({data: {albumDisabled: true, bindDisabled: false}, onLoad: function () { console.log('onLoad'); console.log('onLoad app.globalData.employId = ' + app.globalData.employId); EmployId is bound to if (app.globaldata.employID && app.globaldata.employID! = '') { this.setData({ albumDisabled: false, bindDisabled: true }); }})Copy the code

The console printed the result

onLaunch
onLoad
onLoad app.globalData.employId = 
onLaunch-request-success
Copy the code

It would be nice to wait until the onLaunch request is complete before executing Page’s onLoad method. The approach taken here is to define a callback function. The Page determines whether the current app.globaldata. employId has a value. If not (for the first time), define an app method (callback function) app.employidCallback = employId => {… }. App Page has a callback method defined by Page when judging after requesting success. If there is one, this method will be executed. Because the callback function is defined inside the Page, the method scope this refers to the Page Page.

//app.js app ({onLaunch: function () {wx.request({url: 'test.php', // only for example) data: {}, success: function(res) { this.globalData.employId = res.employId; // Since this is a network request, EmployIdCallback {this.employidCallback (res.employID); if (this.employidCallback); } } }) }, globalData: { employId: '' } })Copy the code
Const app = getApp() Page({data: {albumDisabled: true, bindDisabled: false}, onLoad: Function () {if (app.globaldata.employID && app.globaldata.employID! = '') { this.setData({ albumDisabled: false, bindDisabled: true }); } else {// Since getUserInfo is a network request, EmployIdCallback = employId => {if (employId! = '') { this.setData({ albumDisabled: false, bindDisabled: true }); }}}}})Copy the code

In this way, the desired result can be achieved. The order of execution is:

[App] onLaunch -> [Page] onLoad -> [App] onLaunch sucess callback
Copy the code