将数据从Firebase Firestore加载到数组-angularjs

时间:2018-11-22 23:23:43

标签: angularjs firebase google-cloud-firestore

我正在尝试从Firestore获取数据。连接正常,正在下载数据,但有问题。

我基于https://firebase.google.com/docs/firestore/query-data/get-data的例子。

let list = [];

let products = function GetCollection() {
    firestore.collection("products")
        .get()
        .then(function (querySnapshot) {
            querySnapshot.forEach(function (doc) {
                console.log(doc.id, " => ", doc.data());
                list.push(doc.data());
            });
            $scope.collection = list;
        });
}
products();

console.log("test");

运行此代码后,我的列表为空,但在控制台中列出了所有条目。在调试期间,我注意到在所有GetCollection()函数主体之前执行了console.log(“ test”)的最后一行。 这是同步问题吗?谁能帮我?

1 个答案:

答案 0 :(得分:0)

是,这是预期的行为,console.log("test");将首先执行。由于部分.then(function (querySnapshot是异步调用,因此您在.then内部传递的内容是JavaScript承诺,并且是异步

您还应该使用下面一行中提到的句柄错误 .get(some comde). then ( function -- ). catch ( function (error) { console.log("Error getting cached document:", error); } )

出于测试目的,您也可以使用firebase同步版本的方法,通常firebase api具有相应的同步版本的方法,如果我没记错的话,它们都带有“ sync”后缀