while 循环中的 Firestore 数据库连接

Firestore database connection in a while loop

我在连接到 Firestore 时遇到问题。基本上,在我的 Web 应用程序中,我想从数据库中获取 documentId 以我输入的字符开头的文档。如果它们不存在,我会执行一个 while 循环,在其中随机生成字符并尝试查找以该字符开头的文档:

var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var randomCharacter = Math.floor(Math.random() * characters.length);
this.s = characters.charAt(randomCharacter);
console.log(this.s)


this.getItems(this.s, characters).then((data) => {
  this.items = data
  console.log(data)
  this.item0 = this.items[0]
  console.log(this.item0)
})


async getItems(randomCharPosition, characters) {
const itemRef = await firebase.firestore().collection("junction/" + this.itemId + "/reservations");
return itemRef.orderBy(firebase.firestore.FieldPath.documentId())
.startAt(randomCharPosition).endAt(randomCharPosition + "\uf8ff")
.get().then((querySnapshot) => {
  if (querySnapshot.size == 0) {
    console.log("First document not founded");
    var flag = false
    while (!flag) {
      console.log("No document founded");
      var randomCharacterPosition = Math.floor(Math.random() * characters.length);
      var newChar = characters.charAt(randomCharacterPosition)
      console.log(newChar)
      return itemRef.orderBy(firebase.firestore.FieldPath.documentId()).startAt(newChar).endAt(newChar + "\uf8ff")
        .get().then((data) => {
        if (data.size != 0) {
          console.log("SIZE > 0");
          flag = true
          return data.docs.map(doc => doc.data());
          }
          else console.log("REPEAT")
      })         
    }
  }
  else return querySnapshot.docs.map(doc => doc.data());
}
).catch((error) => {
  console.log("Error getting document:", error);
});

}

问题是 while 循环只执行一次,然后退出,returns未定义

我在 getItems() 函数中做错了什么?

您正在调用 return itemRef.orderBy(... 以便退出 while 循环和 then 函数。

您可以改用 await,让代码等待:

var flag = false
while (!flag) {
  console.log("No document founded");
  var randomCharacterPosition = Math.floor(Math.random() * characters.length);
  var newChar = characters.charAt(randomCharacterPosition)
  const data = await itemRef.orderBy(firebase.firestore.FieldPath.documentId()).startAt(newChar).endAt(newChar + "\uf8ff").get()
  if (data.size != 0) {
    flag = true
    return data.docs.map(doc => doc.data()); // 
  }
  else console.log("REPEAT")
})         

请注意我标记的行。由于它仍然使用 return,因此 that 现在将退出 while 循环,这意味着该标志仍然不是真正需要的,您也可以使用 while (true)

while (true) {
  console.log("No document founded");
  var randomCharacterPosition = Math.floor(Math.random() * characters.length);
  var newChar = characters.charAt(randomCharacterPosition)
  const data = await itemRef.orderBy(firebase.firestore.FieldPath.documentId()).startAt(newChar).endAt(newChar + "\uf8ff").get()
  if (data.size != 0) {
    return data.docs.map(doc => doc.data());
  }
  else console.log("REPEAT")
})