【问题标题】:Loading data from Firebase asynchronously从 Firebase 异步加载数据
【发布时间】:2021-01-03 04:09:43
【问题描述】:

我正在使用带有 Firebase 后端的 React 开发业务经理 Web 应用。我还在编写一个本地 API 来简化 Firebase 功能。我创建了这个方法,它从 Firebase 集合中加载数据并返回一个文档数组。

getDocuments(collection) {
    var documents = [];

    firebase.firestore().collection(collection).get().then(snapshot => {
        snapshot.forEach(doc => {
            documents.push(doc);
        });
    }).then(() => {
        return documents;
    })
}

但是,当我调用该方法并将其分配给稍后打印到控制台的变量时,它会显示 undefined

var employees = getDocuments("employees");
console.log(employees);

我要做的是在调用该方法后使用.then()将已经加载的数据打印到控制台。像这样的:

var employees = getDocuments("employees").then(response => {
    console.log(response);
})

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: javascript node.js firebase promise async-await


    【解决方案1】:

    您的getDocuments 函数似乎过于复杂。这个:

       getDocuments(collection) {    
              return firebase.firestore().collection(collection).get().then(snapshot=>snapshot.docs)
        }
    

    产生与您的函数完全相同的预期结果(一个包含在 Promise 中的文档数组),但执行速度更快,因为它跳过了遍历快照 https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot#docs 中的所有文档

    然后以您喜欢的方式从该函数返回的 Promise 中提取值:

    选项 1(异步/等待)

    let employees= await getDocuments('employees')
    console.log(employees)
    

    选项 2(链接)

    let employees =[] 
    getDocuments('employees').then(response => {
        employees=response 
        console.log(employees) 
    })
    

    说明

    当你这样做时:

    var employees = getDocuments("employees").then(response => {
        console.log(response);
    })
    

    你没有从 getDocuments 收到任何值,因为你一开始没有返回任何东西。

    getDocuments(collection) {
        var documents = [];
    
        firebase.firestore().collection(collection).get().then(snapshot => {
            snapshot.forEach(doc => {
                documents.push(doc);
            });
        }).then(() => {
            return documents; <-- this is returning the value of documents to the parent scope which is 'getDocuments', since the 'then' is related to the 'get' function
        })
    }
    

    【讨论】:

    • 感谢您的详细回答,完全按照您的要求工作!
    • @Erninger 很高兴我能帮上忙!
    【解决方案2】:

    您应该像这样在then 中分配employees

    var employees = [];
    getDocuments("employees").then(response => {
        employees = response;
        console.log(response);
    })
    

    或者如果你在一个异步函数中,你可以这样做

    var employees = await getDocuments("employees");
    console.log(employees);
    

    await 关键字必须在async 函数中完成

    【讨论】:

    • 不幸的是,这不适用于原始的 getDocument() 函数,因为它不返回任何 Promise。但是,调整方法后,它工作得很好!谢谢你的回答!
    猜你喜欢
    • 2021-08-17
    • 1970-01-01
    • 2013-04-07
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 2015-10-20
    相关资源
    最近更新 更多