About the problem of asynchronous login in WeChat Mini Programs? The problem of File execution order and promise problem

at present, I have written the login operation in app.js. After obtaining Wechat"s code, I obtain the authentication access-token from my own server.
the code is as follows

app.js

    onLaunch: function () {
        wx.login({
            success: res => {
                //  res.code  openId, sessionKey, unionId
                config.code = res.code;
                this.initUserInfo();
            }
        })
    },
    
    
    // 
    initUserInfo: function () {
        wx.request({
            url: config.baseUrl + "/index.php?m=Api&c=User&a=initUserInfo",
            method: "POST",
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
                source_type: "wxapp",
                code: config.code,
            },
            success: function (res) {
                if (res.data.status == true) {
                    
                    config.uid = res.data.data.uid;
                    config.accessToken = res.data.data.wxapp_access_token;
          
                } else if (res.data.status == false) {
                    console.log(res.data.data);
                } else {

                }
            }
        })
    },

in another file, met.js, you need to request data through the acquired uid accessToken. The
code is as follows
met.js

    eggGetRemoteWords: function() {

        var self = this;
        wx.request({
            url: app.config.baseUrl + "/index.php?m=Api&c=Learning&a=getLearningWord",
            method: "POST",
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
                uid: app.config.uid,
                access_token: app.config.accessToken
            },
            success: function (res) {
                if (res.data.status == true) {
                    self.setData({
                        "word.wordArray": res.data.data,
                    }) 
                    var total = self.data.word.wordArray.length;
                    self.setData({ "word.wordInfo.total": total });

                } else if (res.data.status == false) {

                } else {

                }
            }
        })
    },

but at present, the function eggGetRemoteWords in met.js is always earlier than the initUserInfo login function in app.j s to execute , so the data cannot be obtained because of js async. Excuse me, how should we deal with this? I learned about promise, how will the current requirements be realized?


eggGetRemoteWords needs to be executed in the success callback of successful login in initUserInfo , so you can define

in this way.
  

re-encapsulate your request with promise

Menu