我想通过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!') }
}