使用云函数获取用户openid,在callFunction里面设置setData失败?

小程序 文章 2022-01-09 19:40 10 0 全屏看文

使用云函数获取用户openid,在callFunction里面设置setData失败?Use cloud function to get the user's openid, and set the setData in the callFunction failed?

使用云函数获取用户openid,在callFunction里面设置setData失败?
getOpenid(){    let that = this;       wx.cloud.callFunction({      name:'getopenid',      complete:res=>{        console.log('云函数获取到的openid:',res.result.openid)        var openid = res.result.openid;        this.setData({          id:openid        })        console.log(that.data.id) #打印出正确的openid      }    })    console.log(that.data.id) #打印的还是openid修改之前的      },

调用getOpenid之后

14,15行输出Page下data的值,14行点开id里面有值,15行取打印不出来??

callFunction函数是有什么恢复现场的操作吗?

我要怎么获取用户的openid呢

Getopenid() {let that = this; Wx. Cloud. Callfunction ({Name: 'getopenid', complete: result = > {console. Log ('openid obtained by cloud function: ', result. Result. Openid) var openid = result. Result. Openid; this. SetData ({ID: openid}) console Log (that. Data. ID) # print out the correct openid}}) console Log (that. Data. ID) # prints the} before openid is modified. After calling getopenid, lines 14 and 15 output the value of data under the page. In line 14, click Open ID, there is a value in it, and line 15 can't print it?? Is there any operation to restore the scene in the callfunction function? How do I get the user's openid

回答:

anmui:

解决了

  onLoad: async function (options) {    await this.getOpenid();    this.getData();  },  async getOpenid(){    let that = this;    await wx.cloud.callFunction({      name:'getopenid',    }).then(res=>{      that.setData({        id:res.result.openid      })    })    console.log(that.data.id)      },
拾忆:

JS异步问题,可以自行百度参考使用 async/await 解决。

anmui:我调用完方法之后,data的id是有值的,但是打印不出来,就是图二那样,这也是异步的问题吗
拾忆:百度下JS异步是怎么回事吧
anmui:好的,感谢!
Mr.Zhao:

异步问题,写到complete里面才正确,跟云函数一点关系都没有

anmui:是setDate写到complete里面吗,现在它就在里面啊
Mr.Zhao:这个啊。如果我说setData写到里面,我不就是眼瞎了吗
anmui:但我想问的setData为啥没有成功啊
Mr.Zhao:执行成功了,只不过是执行顺序问题。取值比赋值先执行的,怎么能对
Mr.Zhao:
anmui:图二里面能查到data里改的结果是咋回事,按理来说应该查不到啊
Mr.Zhao:百度console.log打印和展开后的值不一样
anmui:okkk,非常感谢

-EOF-