首页 > 解决方案 > 在 foreach 循环内将数据推送到 firebase 数据库的问题

问题描述

我正在 Angular8 中构建一个使用 firebase 实时数据库的应用程序。我有一个要添加到数据库的产品列表,但每次我这样做时,我都需要知道该产品是否尚未添加。当我检查snapshot.exists()循环中是否出现问题时,它总是返回 false,因为firebase set 方法是异步的,对 set 函数的调用尚未完成,但循环继续进行下一次迭代。

this.csvData.forEach(product => {
    this.database.database
    .ref(`products/${product.Company}`)
    .once('value', (snapshot) => {
      if (snapshot.exists()) {
        latestIndex = snapshot.numChildren(); 
          this.database.database
          .ref()
          .child('/products')
          .child('/'+product.Company+'/'+ latestIndex)
          .set(product)
          .then(() => {
            // Success 
          })
          .catch(error => {
              // Error
          }); 
      } else {
        //latestIndex = snapshot.numChildren();
        this.database.database
        .ref()
        .child('/products')
        .child('/'+product.Company+'/'+'0')
        .set(product)
        .then(() => {
          // Success 
        })
        .catch(error => {
            // Error
        });          
      } 
    }); // Ends if snapshot doesnt exitts
  }); //foreach ends

我还附上了我拥有的单个产品对象的屏幕截图。 在此处输入图像描述

我需要一些帮助。谢谢

标签: javascriptfirebase-realtime-databaseangular8

解决方案


推荐阅读