Mini Program's question of asynchronously obtaining wx.request data

WeChat Mini Programs"s wx.request is an asynchronous request. Perform background interaction in app.js onLaunch to obtain openid

APP({
    onLaunch:function(){
        //
        wx.login({
            success:res => {
                var code = res.code
                if(code){
                    wx.request({
                        url:xxx,
                        method:xxx,
                        success: res =>{
                            var that = this;
                            console.log("app.js---onLaunch")
                            that.globalData.openid = res.data.openid
                        }    
                    })
                }
            }
        })
    }
})

want to get openid in onReady phase in index.js

const app = getApp()

......

onReady:function(){
    console.log("index.js--onReady")
    console.log(app.globalData.openid)
}

the result is as follows

clipboard.png

my goal is to get the openid on the index.js page and then do the this.setData ({}) assignment, but there is no value at this time because of asynchronism. I have tried several asynchronous methods, promise and cb. I just came into contact with javascript, but the train of thought is not very clear. is there an asynchronous callback?


does the subject want to get openId? This should be backstage to verify who it is, right?
but the question of the subject, I think it is possible to use wx.setStorageSync, in app.js and then wx.getStorageSync


in index.js to encapsulate the method of obtaining openid into a function. In this function, determine whether there is an openid, in storage and go directly to the openid, in storage. If not, initiate a request, get openid, and store it in storage. At present, Mini Program does not seem to have a very reliable method for multi-page communication


the method mentioned above is good, but it is not necessary to store it in storage, just put it in globaldata, and determine if there is no request to get it. After getting it, execute a callback function to pass it in. I suggest that this method be put in util.js


see here Mini Program Development II (Route blocking Design)

Menu