Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

js异步同步问题

在微信小程序中遇到了异步转同步的问题,代码如下:

checkUserState(){
      var _this=this;
      wx.cloud.callFunction({
        name: 'getUserOpenInfo',
        success: async res=>{
          var userOpenId=res.result.event.userInfo.openId;
          console.log("已获取到用户信息:"+JSON.stringify(res.result.event.userInfo));
          _this.data.userInfo.openId=userOpenId;
          if(await Util.userExit(userOpenId)){
            _this.data.messageInfo=Util.pullMessageInfo(userOpenId);
          }
          else{
            await Util.addUser(_this.data.userInfo);
          }
          console.log("我是分割线");
          _this.setData({
            userInfo:_this.data.userInfo,
            messageInfo:_this.data.messageInfo,
            pullMessageComplete:true,
          })
        },
      })
    },

我大概解释一下代码:
CleanShot 2020-05-07 at 11.27.56@2x.png

遇到的问题:获取到openid后,在success回调中应当先执行Util.userExit(userOpenId)方法判断用户在数据库中是否存在,然后执行Util.pullMessageInfo/Util.addUser。最后执行_this.setData

但是现在的情况时,加上await和不加没什么区别,方法的执行是乱的。
CleanShot 2020-05-07 at 11.41.02@2x.png

怎么才能让上述异步方法转同步呢,等待异步方法执行完毕呢。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

userExit 是返回值promise么?函数贴一下


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...