javascript - 如何将 JS 循环变量传递给 FireStore 获取
问题描述
我试图在 for 循环期间将一个变量传递到 firebase 数据库中,但是它在每个循环中返回为相同的值,我在代码中评论了问题发生的地方。
var countElements = document.querySelectorAll("[data-voteCount]");
function displayVotes() {
for (i = 0; i < countElements.length; i++) {
var elementID = countElements[i].dataset.votecount;
docRef = firestore.doc("Votes/product-" + elementID);
console.log(elementID); // when it's logged here the ID's are correct.
docRef.get().then(function(doc) { // how do i pass it into here??
if (doc.exists) {
console.log('document exists ' + elementID); // when logged here the ID is always 1
}
else {
console.log('document not found ' + elementID); // when logged here the ID is always 1
}
});
}
}
<div data-voteCount="1"></div>
<div data-voteCount="2"></div>
<div data-voteCount="3"></div>
解决方案
这就是我会写这样的东西:
async function displayVotes() {
const countElements = document.querySelectorAll("[data-voteCount]");
for (let i = 0; i < countElements.length; i++) {
const elementID = countElements[i].dataset.votecount;
const id = `Votes/product-${elementID}`;
const docSnapshot = await firestore.doc(id).get();
if (docSnapshot.exists) {
console.log(`document exists: ${elementID}`);
}
else {
console.log(`document not found: ${elementID}`);
}
}
}
我转换为async-await
语法,因此您可以更好地控制事情何时发生。缺点是您将执行瀑布式执行,将进行 1 个调用,然后是另一个,依此类推...如果您希望它们并行运行,您可以使用Promise.all()
link。
推荐阅读
- php - 用“span”元素替换“div”元素
- python - 带有字典 `count_if=1` 的 Pandas 聚合被忽略。
- android - 在 iOS 设备上不可见的 Gmail 插件
- java - Rest Assured - 使用 RestAssured 进行测试时出现操作超时错误。但是相同的端点在浏览器中工作正常
- list - 在 Scheme 中搜索定义的列表
- java - 如何获取列表视图?
- wordpress - YOAST 的自定义永久链接问题 - 在 page-template.php 之前显示 category.php
- pandas - 按类别着色 - plotly scattermapbox
- react-native - 如何将 Redux 与 createSwitchNavigator 一起使用?
- ruby-on-rails - Rails循环中断不断循环