
本文深入探讨了在react应用中从firestore等服务异步获取嵌套数据时遇到的常见问题:当尝试使用`foreach`循环收集异步操作的结果时,可能会因为异步回调未被等待而导致返回空数组或未定义的数据。文章详细阐述了如何通过结合使用`array.prototype.map()`生成promise数组,并利用`promise.all()`并发等待所有异步操作完成,从而确保数据正确收集并解决`undefined`访问问题,提供了专业的解决方案和最佳实践。
在现代Web应用开发中,尤其是在使用React和Firestore等NoSQL数据库时,从嵌套集合中异步获取数据是一个常见的需求。然而,不恰当地处理异步操作的集合可能会导致数据访问问题,例如尝试访问数组元素时得到undefined。这通常发生在开发者尝试在forEach循环中执行异步操作并收集结果时。
考虑以下一个从Firestore获取文档及其子集合“objectives”的函数GetObjectives:
import { collection, getDocs } from 'firebase/firestore';
import { db } from './firebaseConfig'; // 假设你的db实例已配置
export async function GetObjectives(docId) {
try {
const querySnapshot = await getDocs(collection(db, "users", "userIdNotAvailableForTheMoment", "documents", docId, "nodes"));
const objectivesArray = [];
// 问题所在:forEach不会等待内部的异步操作
querySnapshot.forEach(async (nodeDoc) => {
const nodeId = nodeDoc.id;
const objectivesQuerySnapshot = await getDocs(collection(db, "users", "userIdNotAvailableForTheMoment", "documents", docId, "nodes", nodeId, "objectives"));
const objectivesData = objectivesQuerySnapshot.docs.map((objectiveDoc) => ({
...objectiveDoc.data(),
id: objectiveDoc.id
}));
objectivesArray.push(objectivesData);
});
// objectivesArray 在此处很可能为空,因为forEach内部的异步操作尚未完成
return objectivesArray;
} catch (error) {
console.error('Error during the recuperation of objectives : ', error);
return null;
}
}当使用上述函数并尝试访问返回结果的第一个元素时,例如result[0],可能会得到undefined,即使console.log(result)可能看起来像一个包含数据的数组。这是因为Array.prototype.forEach方法本身是同步的,它不会等待其回调函数内部的异步操作完成。因此,当forEach循环结束后,objectivesArray很可能仍然是空的,或者只包含了部分未完全解析的数据,导致在函数返回时,外部调用者接收到一个空或不完整的数组。
要正确地收集多个异步操作的结果,我们需要确保所有内部的异步操作都已完成。JavaScript提供了Promise.all()方法来解决这个问题,它接收一个Promise数组,并返回一个新的Promise,该Promise在所有输入的Promise都解析后解析,并返回一个包含所有解析值的数组。
为了生成一个Promise数组供Promise.all()使用,我们可以利用Array.prototype.map()方法。map方法会为数组的每个元素调用一次回调函数,并使用回调函数的返回值创建一个新数组。如果回调函数是async函数,它将返回一个Promise,因此map会生成一个Promise数组。
以下是GetObjectives函数的修正版本:
import { collection, getDocs } from 'firebase/firestore';
import { db } from './firebaseConfig'; // 假设你的db实例已配置
export async function GetObjectives(docId) {
try {
const querySnapshot = await getDocs(collection(db, "users", "userIdNotAvailableForTheMoment", "documents", docId, "nodes"));
// 使用map生成一个Promise数组
const objectivesPromises = querySnapshot.docs.map(async (nodeDoc) => { // 注意这里是querySnapshot.docs
const nodeId = nodeDoc.id;
const objectivesQuerySnapshot = await getDocs(collection(db, "users", "userIdNotAvailableForTheMoment", "documents", docId, "nodes", nodeId, "objectives"));
// 返回一个包含所有子目标数据的数组
return objectivesQuerySnapshot.docs.map((objectiveDoc) => ({
...objectiveDoc.data(),
id: objectiveDoc.id
}));
});
// 使用Promise.all等待所有Promise解析,并返回一个包含所有结果的数组
return Promise.all(objectivesPromises);
} catch (error) {
console.error('Error during the recuperation of objectives : ', error);
return null;
}
}querySnapshot.docs.map(async (nodeDoc) => { ... }):
LimeSurvey是一款问卷调查管理系统,具有问卷的设计、修改、发布、回收和统计等多项功能,集成了调查程序开发、调查问卷的发布以及数据收集等功能,使用它,用户不必了解这些功能的编程细节。 LimeSurvey 3.14.2 中文版 更新日志:2018-08-07 -修正问题#13878:向用户组发送电子邮件-显示问题; -修正问题#13902:LimeSurvey尝试在编辑问题时更新响
154
return Promise.all(objectivesPromises):
调用修正后的GetObjectives函数将更加直观和可靠:
// 假设 sortDocuments[parseInt(selectedDocument)].id 提供了正确的docId
GetObjectives(sortDocuments[parseInt(selectedDocument)].id)
.then((result) => {
console.log(result); // 应该会输出一个包含所有目标数据的嵌套数组
console.log(result[0]); // 现在应该能正确访问第一个节点的 objectives 数组
})
.catch((error) => {
console.error("Failed to retrieve objectives:", error);
});在这种情况下,result将是一个类似以下结构的数组:
[
[
{
"parents": [],
"childrens": [],
"content": "value",
"id": "VULpo5mPCc2kckLC9BCy",
"title": "value"
}
],
[
{
"parents": [],
"childrens": [],
"content": "value",
"id": "ANOTHER_ID",
"title": "another value"
}
]
]现在,result[0]将正确地访问到第一个节点的目标数组。
通过采纳Promise.all()与map的模式,开发者可以有效地管理复杂的异步数据流,确保数据被正确、完整地收集,从而避免因异步操作未完成而导致的undefined或空数据问题。
以上就是正确使用Promise.all()解决React中异步数据收集问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号