从Firebase Firestore参考获取异步值 [英] get asynchronous value from firebase firestore reference

查看:51
本文介绍了从Firebase Firestore参考获取异步值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Firebase Firestore数据库中从该诺言中获取名称值:

I'm trying to get the name value from this promise from firebase firestore database:

(至于信息,我有一个场所集合,其场所包含一个名称,而ownerReference引用一个仅包含名称的所有者文档.)

(as for information I have a places colection that have a place containing a name and a ownerReference that references an owner document containing a name only.)

var names: any = [];
this.props.places.snapshot.docs.forEach((doc : any) => {
  const place = doc.data()
  place.ownerReference.get().then((snap : any) => {
    name.push(snap.data().name);
    console.log(names);
  })
});
console.log(names);

第一个控制台日志返回所需的数据,最后一个控制台返回一个空的对象,我知道这是由于promise的异步特性而发生的,但是我如何才能获得分配给该变量的所需值呢?

the first console log return the desired data, the last one returns an empty object, I know this is happening because of the asynchronous nature of a promise , but how can I get the desired value assigned to this variable?

推荐答案

将每个get()中的所有promise收集到一个数组中,然后使用Promise.all()等待它们全部完成.之后,在回调中迭代生成的快照.

Collect all the promises from each get() into an array, then use Promise.all() to wait until they are all done. Iterate the resulting snapshots in the callback after that.

const promises = []
this.props.places.snapshot.docs.forEach((doc : any) => {
    const place = doc.data()
    promises.push(place.ownerReference.get())
})

Promise.all(promises).then(snapshots => {
    const names = []
    snapshots.forEach(snapshot => {
        names.push(snapshot.data().name)
    })
    console.log(names);  // this prints what you want
})

这篇关于从Firebase Firestore参考获取异步值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆