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

Get all list from one firestore collection with VueJS

我想通过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.
    },

不要将 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!') }
}