收藏
回答

如何解决async/await实现同步时出现的问题?

新手一枚,看文档也看不出问题所在,所以请教一下各位大佬们
以下是代码,想使用async/await解决问题,但是只执行了this.getUser_openid(),而没有继续执行this.getCollect()
代码简陋还未优化,还请见谅,求各位大佬看一看解答一下,怎么才能让this.getCollect()也执行。

init:async function(){
    await this.getUser_openid()
    await this.getCollect()
},
getUser_openid:function(){
    let that = this
    return new Promise((resolve, reject) => {
      // 获取用户信息
      if (wx.getStorageSync("login_status") != "") {
        // 获取用户信息
        wx.getSetting({
          success: res => {
            if (res.authSetting['scope.userInfo']) {
              console.log('已授权')
              wx.setStorageSync("login_status", true)
              // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
              wx.getUserInfo({
                success: res => {
                  that.setData({
                    login_status: true,
                    me_image: res.userInfo.avatarUrl,
                    me_nickname: res.userInfo.nickName,
                    me_address: res.userInfo.province + ', ' + res.userInfo.country,

                    userInfo: res.userInfo

                  })
                  wx.cloud.callFunction({
                    name: 'login',
                    complete: res => {
                      console.log('云函数获取到的openid:', res.result.openid)
                      var openid = res.result.openid;
                      that.setData({
                        openid: openid
                      })
                    
                    }
                  })
                
                }
              })
            }
          }
        })
      }
    })
  },
getCollect:function(){
    let that = this
    return new Promise((resolve, reject) => {
      let openid = that.data.openid
      const db = wx.cloud.database()
      db.collection("collect_menu").where({ openid: openid }).get().then(res=>{
        let collect_list = that.data.collect_list
        const db2 = wx.cloud.database()
        console.log(res.data.length)
        if(res.data.length)
        {
          for (var i = 0; i < res.data.length; i++){
            db2.collection("foods").where({_id:res.data[i].menu_id}).get().then(res2=>{
              console.log(res2.data.length)
              if(res2.data.length)
              {
                collect_list.push(...res2.data)
              }
            })
          }
          that.setData({ collect_list })
          console.log(that.data.collect_list)

        }
      })
    })
},


回答关注问题邀请回答
收藏

1 个回答

  • 莫名流年
    莫名流年
    2020-06-07

    Promise回调呢?

    2020-06-07
    有用
    回复 2
    • 莫名流年
      莫名流年
      2020-06-07
      你只定义了Promise函数,Promise的话,你需要在调用完成后去调用 resolve 或者 reject 抛出执行结果. 懂了吧?
      2020-06-07
      回复
    • 标
      2020-06-07
      哦哦,好的,这样啊,了解了,谢谢大佬啦
      2020-06-07
      回复
登录 后发表内容
问题标签