Estaba ejecutando firebase cuando vi un comportamiento extraño que no puedo entender. Mi html se ve así:
<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! *** } Problema 1: ejecución asíncrona sin espera.
Problema 2: el índice no está definido después de leer e iterar datos de firebase. Por favor, ayuda ya que estudié js durante más de un año y ahora me siento como un novato.
Gracias Bergi ( Perfil ): De hecho, es una espera de nivel superior (una función en moduleJS).
Lea más sobre esto aquí: https://v8.dev/features/top-level-await
¡Gracias! Dharamraj ( Perfil ) => el índice querySnapshot.docs.forEach() funciona perfectamente bien ahora.