javascript - 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()的情况下最终执行?
解决方案
发生这种情况的原因是因为您的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);
}
推荐阅读
- firebase - 从 firebase 获取数据后无法呈现 react-native 组件
- apache-storm - 阿帕奇风暴与阿帕奇气流
- python - WTForms Flask(wtf_flask) 验证器如何包含 RadioField 的“必需”属性
- c# - 有什么方法可以从 SQL Server 数据库调用日期时间,多个日期时间之间有一些时间间隔差异
- angular - CanActivate 的行为与 Angular 7 与 firebase 的行为不符
- python - 使用 RASA NLU 训练模型时出现 TensorFlow 错误
- javascript - 在按钮上单击显示数据库中单个用户的纬度和经度并显示在谷歌地图上
- dialogflow-es - 将 DialogFlow 提取参数映射到数据库列值
- python-3.x - 如何使用 spark_task 和 pythonOperator 向/从 Airflow X_COM 推/拉?
- php - Apache2 网络服务器上的 $_GET["_url"] 不工作