【问题标题】:Firestore get() method code is executing at the very end of the functionFirestore get() 方法代码在函数的最后执行
【发布时间】:2021-03-21 16:47:35
【问题描述】:

以下是我的 Firestore 代码。您会看到 get 方法在函数的最后执行。即使它是在开始时声明的。

我很沮丧。如果它在最后执行,那么这个有什么用。

我不知道为什么 Firestore 的人要编写这种类型的代码。他们在他们的网站上没有任何答案。

         function bookingsSubmit() { //This function saves the data of 
         //declaring database and all collections
         var db = firebase.firestore();
     const userColl = db.collection('users');
     const adminColl = db.collection('Admincrates');
     const bookingscoll = db.collection('bookings');
     const taskscoll = db.collection('tasks');

     //------Getting User Email
     var u = firebase.auth().currentUser.email;
     var username;
     var lngth;
     var curList = [];
     //---------Getting Username
     userColl.doc(u).get().then((doc) =>{ //This is going into user collection for user's name
              //We got all the fields of user and going through all the fields
                 username = doc.data().name;
                 console.log(username);
                 lngth = doc.data().currencyList.length;
                 for(var l = 0; l<lngth;l++){curList.push(doc.data().currencyList[l])}
             });

     console.log(curList);
     //---------Getting the Booking Id and Incrementing the booking Id value
     taskscoll.doc('bookingId').update({ //Increment
         id: firebase.firestore.FieldValue.increment(1)
     });
     var bkngId;
     taskscoll.doc('bookingId').get().then((doc)=> { bkngId = doc.data().id}); //Getting Booking Id and saving                              into a variable 
 console.log(bkngId);

 //---------Getting Table values.
  var tbl_user = document.getElementById('booking_tbl'); //Reading the table of the user page middle 
  for(var i = 1; i < lngth; i++) {

  }

 var docData = {
     email: u,
     name: username,
     bookingId: bkngId,
     timestamp: firebase.firestore.FieldValue.serverTimestamp(),
     arrayExample: [5, true, "hello"],
     nullExample: null,
     objectExample: {
         a: 5,
         b: {
        nested: "foo"
         }
     }
 };
 console.log(docData);
 bookingscoll.add(docData).then(() => {
console.log("Document successfully written!");
});

 }

【问题讨论】:

  • 你可能想玩异步/等待 - 对我来说它彻底清理了我的代码。

标签: javascript firebase web google-cloud-firestore firebase-security


【解决方案1】:

.get() 操作是异步的 - 您随后的 .then() 等待 .get() 完成 - 但它也返回一个承诺,您的代码不会等待。

详细了解 Javascript“事件循环”将非常有益。前台(即同步)将优先,除非您在某些时候创造机会 - 即某种形式的等待 - 以使“后台”(事件驱动)代码发生。在您的情况下,由于您不等待 .get().then() 的结果,因此您的代码会在实际的 .get() 事件发生之前执行到函数的末尾。

如果您可以选择,我建议使用async/await 语法,这通常可以帮助使这一点更加明显。不要将async/await.then() 混用 - 这只会导致心痛(并且难以调试)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2018-05-12
    • 2016-07-07
    相关资源
    最近更新 更多