小程序云函数,为啥这个外部获取不到数据?
App({
globalData: {
userInfo: null,
openid:null
},
onLaunch() {
wx.cloud.init({
env:'hope-7g8c1n2f6997c60e' //初始化
})
//获取用户openid
wx.cloud.callFunction({
name:"comlogin",
success:res => {
this.globalData.openid = res.result.openid
//数据库查找
wx.cloud.database().collection('user').where({
_openid:res.result.openid
}).get().then(result =>{
console.log("1.内部未赋值前:", this.globalData.userInfo)
this.globalData.userInfo = result.data[0]
console.log("2.内部赋值后:", this.globalData.userInfo)
})
console.log("3.数据库查询外部", this.globalData.userInfo)
}
})
console.log("4.callFunction外部",this.globalData.userInfo)
}
})
//获取用户openid
wx.cloud.callFunction({
name: "comlogin",
// 这里是异步处理
success: res => {
this.globalData.openid = res.result.openid
//数据库查找
wx.cloud.database().collection('user').where({
_openid: res.result.openid
}).get().then(result => { // 这里也是异步处理
console.log("1.内部未赋值前:", this.globalData.userInfo)
this.globalData.userInfo = result.data[0]
console.log("2.内部赋值后:", this.globalData.userInfo)
})
console.log("3.数据库查询外部", this.globalData.userInfo)
}
})
console.log("4.callFunction外部", this.globalData.userInfo)
这两处是异步的缘故吧,如果想让”4.callFunction外部“和"3.数据库查询外部"拿到数据,可以改成同步的方式。
小程序赋值要用shis.setData()的,不能直接赋值
你在getApp()下面打印下 app看看是什么?
然后用getApp().globalData.userInfo 直接取值.
因为获取数据的操作是异步的,你同步执行的代码是会在你还没有拿到数据的时候就执行完,所以4、3、1输出结果是null
下方是异步操作
wx.cloud.database().collection('user').where({
_openid:res.result.openid
}).get()