【问题标题】:How to get value returned by promise outside the scope using Vue and Firestore如何使用 Vue 和 Firestore 在范围外获取 Promise 返回的值
【发布时间】:2020-10-17 03:15:31
【问题描述】:

我发现很难在其他方法中使用 firestore 承诺返回的值,因为我越来越不确定。我尝试以下面的方式使用 async/await,但仍然没有成功。

get_board_details(){         db.collection('members').where('board_id','==',this.$route.params.groupslug).get().then(querySnapshot=>{
                     querySnapshot.forEach( async doc=>{
                       this.owner_id  = await doc.data().owner_id;
                      })
                    })
                  console.log(this.owner_id)
                  },

【问题讨论】:

    标签: javascript firebase vue.js google-cloud-firestore


    【解决方案1】:

    尝试以下操作,确保您的 this.$route.params.groupslug 事先正确。

    get_board_details(){      
     db.collection('members').where('board_id','==',this.$route.params.groupslug).get().then(querySnapshot=>{
                         querySnapshot.forEach( doc=>{
                           this.owner_id  = doc.data().owner_id;
                           console.log(this.owner_id)
                          })
                        })
                      },
    

    【讨论】:

    • 谢谢,我在尝试这个时得到了预期的结果,但是如果我尝试在其他方法中使用 this.owner_id,我得到了未定义
    • 在其他方法中使用 owner_id 之前,您需要检查 null/undefined。原因是您的 db 调用是一个异步函数。我的代码工作的原因是因为 console.log 在 .then() 中。
    猜你喜欢
    • 2020-08-24
    • 2022-01-04
    • 2019-11-11
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多