鍍金池/ 問答/Java  Linux  HTML/ 小程序wx.request 數(shù)據(jù)異步獲取疑問

小程序wx.request 數(shù)據(jù)異步獲取疑問

微信小程序的wx.request是異步請求,在app.js onLaunch里進行后臺交互獲取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
                        }    
                    })
                }
            }
        })
    }
})

在index.js中 onReady階段想獲取openid

const app = getApp()

...省略...

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

結(jié)果如下圖

clipboard.png

我的目的是想在index.js頁面獲取openid然后進行this.setData({})賦值操作,但由于異步的關系,這時候還沒有值。我嘗試了幾種異步方式,promise和 cb的方法,剛接觸javascript不久,思路還不是很清晰,有異步回調(diào)大神指點一二嗎?

回答
編輯回答
拮據(jù)

建議把獲取openid的方法封裝成一個函數(shù),在這個函數(shù)里,判斷storage里面是否有openid,有的話直接去storage里面的openid,沒有的話,發(fā)起請求,獲得openid,并且存儲到storage里面。目前來來說小程序多頁面通信貌似沒有很靠譜的方法

2017年12月25日 15:44
編輯回答
悶騷型

樓上說的方法挺好,不過沒必要存在storage里,就放globaldata里就行,判斷沒有就發(fā)起請求獲取,取得以后執(zhí)行一個回調(diào)函數(shù)傳進來,我建議這個方法放在util.js里

2017年6月5日 15:20
編輯回答
編輯回答
笨尐豬

題主是想要獲取 openId ?這個應該是后臺來驗證是誰吧?
但是題主的問題我覺得可以這樣,不用全局變量,在 app.js 用 wx.setStorageSync,然后在 index.js 用 wx.getStorageSync

2017年9月28日 23:27