首页 > 解决方案 > Javascript firebase 函数未按定义的顺序执行

问题描述

我有一个使用 google firebase - firestore 数据库的网站。我有某些功能可以从 firestore 获取数据并在页面加载时在网站上显示数据。

all_data = [];

//Get all documents in collection
function getAllDocuments() {
  console.log('getAllDocuments() executed');
  db.collection("All data").get().then((querySnapshot) => {
    console.log('Getting documents from firestore...');
    querySnapshot.forEach((doc) => {
      //Creating object
      data_t = new dbData;
      all_data.push(data_t);
    });
  });
  console.log('All data:', all_data.length);
}

//Display documents
function displayDocuments(data) {
  console.log('displayDocuments() executed');
  //Other lines of code
}

//Functions to run on page load
function pageLoad() {
  getAllDocuments();
  displayDocuments(all_data);
}
window.onload = pageLoad;

但是,这些函数是在从 firebase 检索数据之前执行的。因此,我的网站加载为空白页面。我必须再次执行displayDocuments()才能在屏幕上显示数据。
我理解这背后的问题。该网页在页面加载时没有从 Firebase 获取我的文档。即使pageLoad()执行getAllDocuments(),它最初也会跳过db.collection.get()。这个方法只有在window.onload执行之后才会执行,也就是我的pageLoad()全部执行完之后。我的控制台输出看起来像

getAllDocuments() 已执行
所有数据:0 displayDocuments() 已
执行
从 firestore 获取文档...

有谁知道为什么db.collection.get()没有按定义的顺序执行?db.collection().get()如何在不调用 getAllDocuments()的情况下最终执行?

标签: javascripthtmlfirebasegoogle-cloud-firestore

解决方案


发生这种情况的原因是因为您的getAllDocuments函数在 promise 可以解决之前完成了它的执行。

您可以做的是使用 await 进行getAllDocuments异步并等待 promise 解决,并pageLoad()使用 await 从函数中调用它。IE

all_data = [];

async function getAllDocuments() {
    console.log('getAllDocuments() executed');
    const querySnapshot = await db.collection("All data").get();
    querySnapshot.forEach((doc) => {
      //Creating object
      data_t = new dbData;
      all_data.push(data_t);
    });
    console.log('All data:', all_data.length);
}

async function pageLoad() {
  await getAllDocuments();
  // displayDocuments(all_data);
}

推荐阅读