【问题标题】:Async/await on firebase queries异步/等待 firebase 查询
【发布时间】:2021-02-18 16:53:05
【问题描述】:

我再次请求您帮助解决 firebase 问题。现在我已经把 async/await 放在我的函数之外使用来自快照的数据,但仍然没有工作:


        database.ref('adress').once('value', (snapshot) => {
            snapshot.forEach(async function (childSnapshot) {           
                 const childKey = await childSnapshot.key;
                 const childData = await childSnapshot.val();
                         
    });             
});


我能得到一些帮助吗?

【问题讨论】:

    标签: javascript firebase firebase-realtime-database async-await


    【解决方案1】:

    我认为您在 firebase 中使用异步函数的方式错误

    你应该这样使用

    async funcion getAdress(){
      try{
         const snapshot = await database.ref('adress').once('value');
    
         snapshot.foreach();
      }catch(err){
         console.error(err);
      }
      
    }
    
    

    【讨论】:

    • 我如何从中获取``` snapshot.value() ```?
    【解决方案2】:

    我不确定我是否完全遵循了您的问题,但使用 https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document 的示例作为起点,我们可以重新编写代码以使用 await 而不是 then。

    var docRef = db.collection("cities").doc("SF");
    try {
      var doc = await docRef.get()
    
      if (doc.exists) {
        console.log("Document data:", doc.data());
      } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
      }
    } catch (err) {
        console.log("Error getting document:", error);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-15
      • 1970-01-01
      • 2018-11-06
      • 2020-06-19
      • 2021-04-16
      • 2018-09-13
      • 2018-05-04
      • 2018-12-11
      • 2018-03-12
      相关资源
      最近更新 更多