問題場景,在我index.js里面需要用到onLunch函數中得到的值,但是在小程序進入啟動,已進入index.js時,獲取的值不會等到onlunch函數中執行完在拿,所以這時候的index.js所需要的那個值是一個空的。
解決思想:通過promise的方法來解決異步。
使用:在app.js的onlunch函數中:
getAuthKey: function () { console.log("method") var that = this; return new Promise((resolve,reject)=>{ //調用登錄接口 wx.login({ success: function (res) { var code = res.code// 登錄憑證 console.log(code, "code碼") that.globalData.code = code wx.getUserInfo({ success: function (res2) { // that.globalData.userInfo = res.userInfo typeof cb == "function" && cb(that.globalData.userInfo) that.globalData.userInfo = res2.userInfo // that.globalData.userInfo2 = res2.userInfo.avatarUrl console.log("用戶信息", res2) wx.request({ url: getApp().globalData.url + 'ywxlogincontroller/login', header: { 'content-type': 'application/x-www-form-urlencoded' }, method: "POST", data: { code: getApp().globalData.code, key: "keyA965C612A7366F79B847AF301E65C5C6", }, success: res => { wx.hideLoading() console.log(getApp().globalData.code, "后台數據", res.data) getApp().globalData.userData = res.data.data; getApp().globalData.userId = res.data.data.user.id; if (res.data.data) { wx.switchTab({ url: '../index/index', success: () => { wx.showToast({ title: '登錄成功', }) console.log("登錄成功", getApp().globalData.userData) }, }) } else { wx.showToast({ title: '登錄失敗', icon: "none" }) } resolve(res); } }) }, fail: function () { reject('error'); } }) } }) }) }
在index.js中:
const app = getApp() app.getAuthKey().then(res=>{ // 這里就可以在onlunch函數執行完后,在這里等待拿到所需要的值。 })
這里也可以使用 async/await es7新特性 配合着promise使用同樣可以達到上面的效果。async/await使用方式可以借鑒我的博客 https://www.cnblogs.com/xuhuang/p/9806255.html
