使用VueJS从一个firestore集合中获取所有列表

问题描述 投票:0回答:1

我想通过firestore查询显示所有用户列表。但我坚持承诺链。要查询集合的文档,需要两个异步步骤。我怎么能等到填满所有列表集。

这是我的代码。我希望我的fetchUsers()填充数组没有回调链。

const db = firebase.firestore();

export default {
  data: () => {
    return {
      users: [],
    }
  },
  mounted: function() {
      this.fetchUsers()
      console.info('mounted, users:', this.users) // // => at this point, this.users is not yet ready.
  },
  computed: {
      items: function() {
          return this.users
      }
  },
  methods: {
    async fetchUsers () {
        await db.collection('users').get()
            .then(snapshot => {
                snapshot.forEach( doc => {
                    const user = doc.data()
                    console.log('forEarch:' , user)
                    user.id = doc.id
                    this.users.push(user)
                })
            })
            .catch(error => {
                console.error(error)
            })
        console.debug('fetchUser return: ', this.users)  // => at this point, this.users is not yet ready.
    },
javascript firebase vue.js google-cloud-firestore es6-promise
1个回答
1
投票

不要将async / await语法与then / catch混合使用

const query = db.collection('users')

async fetchUsers () {
    try {
        const { docs } = await query.get()

        this.users = docs.map(doc => {
          const { id } = doc
          const data = doc.data()
          return { id, ...data }
        })

        console.log('Loaded users', this.users)
    } catch (error) { throw new Error('Something gone wrong!') }
}
© www.soinside.com 2019 - 2024. All rights reserved.