虽然app.js先于index.js。但是修改app.js中的全局变量是异步请求,如果你想在index.js里获取app.js修改后的值,那么需要使用promise来实现异步。
//app.js
App({
globalData: {
url: 'XXX'
userInfo: null
},
// 检测授权
getopenid: function (parentid = '') {
return new Promise((resolve, reject) => {
var urls=this.globalData.url;
var that=this;
wx.login({
success (res) {
if (res.code) {
//发起网络请求
wx.request({
url: urls+'shop/login/get_openid',
data: {
code: res.code,
parentid:parentid,
},
method: 'POST',
success: res => {
that.globalData.userinfo=res.data.value.userinfo;//赋值用户信息
// that.wxpay();
resolve(that.globalData.userinfo) //这里是关键,切记
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
})
},
// index.js
data: {
img: '',
userinfo: {},
list: []
},
onLoad: function(options) {
app.getopenid().then(res => {
var that = this
that.setData({
userinfo: res[0].wxno
})
console.log(that.data.userinfo)
})
}
因为要首先加载index页面,所以需要使用异步请求,在其他页面的话,可以直接使用app.globalData.userInfo