【问题标题】:weird behavior await running without async奇怪的行为等待在没有异步的情况下运行
【发布时间】: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


【解决方案1】:

谢谢你,Bergi (Profile): 它确实是一个顶级的 await(moduleJS 中的一个特性)。

在此处了解更多信息:https://v8.dev/features/top-level-await

谢谢! Dharamraj (Profile) => querySnapshot.docs.forEach() 索引现在可以正常工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-13
    • 2018-07-18
    • 2021-11-14
    • 2013-07-22
    • 1970-01-01
    • 2023-02-21
    • 2022-01-08
    • 2012-11-15
    相关资源
    最近更新 更多