大佬教程收集整理的这篇文章主要介绍了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() 的情况下在最后执行?
您需要等待第一个函数的结果,因为它执行异步操作。您可以通过直接返回承诺来实现。在这种情况下,您不需要 all_data 全局变量,因为您可以从 promise 中返回它。
这样的事情应该对你有用:
//Get all documents in collection
function getAllDocuments() {
console.log('getAllDocuments() executed');
return db.collection("All data").get().then((querySnapshot) => {
console.log('GetTing documents from firestore...');
return querySnapshot.map((doC) => {
//CreaTing object using doc
// ....
return new dbData;
});
});
}
//Display documents
function displayDocuments(data) {
console.log('displayDocuments() executed');
//Other lines of code
}
//Functions to run on page load
function pageLoad() {
getAllDocuments().then(all_data => displayDocuments(all_data));
}
window.onload = pageLoad;
,
发生这种情况的原因是您的 getAllDocuments
函数在 promise 解决之前完成了它的执行。
您可以做的是使getAllDocuments
异步并使用await 等待promise 解析,然后使用await 从pageLoad()
函数中调用它。即
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);
}
以上是大佬教程为你收集整理的Javascript firebase 函数未按定义的顺序执行全部内容,希望文章能够帮你解决Javascript firebase 函数未按定义的顺序执行所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。