【发布时间】:2021-11-18 09:33:17
【问题描述】:
当我看到一个我无法理解的奇怪行为时,我正在运行 firebase。我的 html 看起来像这样:
<script src="https://www.gstatic.com/firebasejs/8.2.6/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.6/firebase-firestore.js"></script>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp, } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-analytics.js";
import { getFirestore, collection, getDocs, addDoc } from 'https://www.gstatic.com/firebasejs/9.0.2/firebase-firestore.js';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
const firebaseConfig = { ... } //firebase config
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const db = getFirestore(app);
const querySnapshot = await getDocs(collection(db, "location")); *** //await is running without async! ***
console.log(querySnapshot)
querySnapshot.forEach((doc, index) => {
// do something with doc
*** // index always returns undefined! ***
}
问题 1:异步运行而无需等待。
问题 2:从 firebase 读取和迭代数据后未定义索引。
请帮忙,因为我学习了 js 一年多,现在我感觉自己像个完全的新手。
【问题讨论】:
-
不确定缩进的奇怪变化,但看起来像top-level await。
-
"index 总是返回 undefined!" 使用
querySnapshot.docs.forEach()而不是querySnapshot.forEach()
标签: javascript arrays firebase google-cloud-platform google-cloud-firestore