【问题标题】:forEach() does not update the values inside a database callforEach() 不会更新数据库调用中的值
【发布时间】:2021-06-29 06:11:05
【问题描述】:

下面的 sn-p 表示数据库的侦听器,它在更改时返回多个对象(每个对象代表一个文档)然后它将获得idquantity该对象然后它将遍历每个对象并将object.price元素添加到每个对象并再次调用数据库然后它将使用quantityobject.price元素来获取每个对象的总量但是问题是quantityid 没有按预期为每个对象更新,而不是quantity 值将始终是最后一个对象quantity 的值。 但是当我尝试在forEach() 中获取idquantity 的值时,但是一旦在调用数据库的函数内部和在它外部,如下面的sn-p 所示,问题正在发生仅在函数内部,当尝试在函数之后获取quantity 值时会出现相同的问题(我将在 sn-p 之后将已登录的内容的副本放在控制台中

  useEffect(() => {
   
    db.collection("users").doc("4sfrRMB5ROMxXDvmVdwL").collection("basket").onSnapshot((docs) => {
        const oneSubTotal = [];
        let array = [] 
        let object = undefined;
        let id = undefined;
        let quantity = undefined;
        docs.forEach(  doc =>{
                object = doc.data()
                id = object.id;
                quantity = object.quantity
                
          
                console.log( " the quantity  before is " + quantity)
                console.log(" the id before is " + object.id)
                db.collection("products").doc(id).get().then( (e)=>{
                    object.price =  (e.data().price);
                    console.log( " the quantity inside is " + quantity)
                    console.log(" the id inside is " + id)
                    oneSubTotal.push(object.price * quantity)     
                     
                })
                    console.log( " the quantity after is " + quantity)
                    console.log(" the id after is " + id)
        })
  });
  }, [])

这是控制台中记录的内容

 the quantity  before is 9
 the id before is 1
 the quantity  before is 10
 the id before is 2
 the quantity inside is 10
 the id after is 2
 the quantity inside is 10
 the id after is 2
 the quantity after is 10
 the id after is 2
 the quantity after is 10
 the id after is 2

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore async-await


    【解决方案1】:

    Tl;博士:

    • 在循环之前创建一个名为promises 的变量并用一个空数组对其进行初始化:let promises = [];
    • 在循环内部,而不是执行承诺(通过调用 .thenawait),将承诺推送到 promises 数组
    • 一旦在循环之外,调用Promise.all(promises) 来解析所有推入promises 数组的承诺,这将返回一个包含所有响应的数组。

    当您想在 for-each 循环(或任何与此相关的循环)中使用 Promise 时,您不应该在循环内执行该 Promise。相反,您应该将它推入一个 promise 数组(在循环之外),并在循环结束后,使用Promise.all 一次性解决所有这些问题。像这样:

    useEffect(() => {
      db.collection("users")
        .doc("4sfrRMB5ROMxXDvmVdwL")
        .collection("basket")
        .onSnapshot((docs) => {
          const oneSubTotal = [];
          let array = [];
          let object = undefined;
          let id = undefined;
          let quantity = undefined;
          let promises = [];
          docs.forEach((doc) => {
            object = doc.data();
            id = object.id;
            quantity = object.quantity;
            console.log(" the quantity  before is " + quantity);
            console.log(" the id before is " + object.id);
            promises.push(db.collection("products").doc(id).get());
            console.log(" the quantity after is " + quantity); // quantity won't change here because we're not fulfilling the promise yet.
            console.log(" the id after is " + id); // same as above, this won't update before the promise is fulfilled, which is happening below
          });
          Promise.all(promises).then((allDocumentsFromForLoop) => {
            allDocumentsFromForLoop.map((document) => {
              console.log( " the quantity inside is " + quantity)
              console.log(" the id inside is " + document.data().id)
              oneSubTotal.push(document.data().price * quantity);
            });
          });
        });
    }, []);
    

    【讨论】:

    • 这段代码解决了id 的问题,但由于某种原因,quantity 仍然没有为每个文档更新@Fardeen Panjwani
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 2019-07-07
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多