首页 > 解决方案 > 如何将 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>

标签: javascriptfirebasegoogle-cloud-firestore

解决方案


这就是我会写这样的东西:

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


推荐阅读