javascript - 在 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
我需要一些帮助。谢谢
解决方案
推荐阅读
- python-3.x - 无法使用 python 从 redmart 获取产品标题
- javascript - Alert On input Field 在表单中单击 3 次
- javascript - 使用 html 和 javascript 进行表单验证
- c# - 打开 XML 创建多个工作表
- c# - 在 HttpRequestException 之后使用 Polly 重试
- java - Java中Double类型的“无穷大”如何
- python-2.7 - 如何在机器人框架中使用监听器
- python - 从文本文件中为实体创建带有注释的 json 文件,并将 startIndex 和 endIndex 附加到字典中
- firebase - 当应用程序处于后台(最小化)时,推送通知不起作用 - iOS
- javascript - 下载文件到本地计算机发送附加到消息不和谐