【发布时间】:2022-01-27 12:15:16
【问题描述】:
我有一种情况,我必须多次从多个 api 获取数据,以便将所有数据转换为嵌套格式。基本上,我必须从一个 api 获取可用组的列表,然后单独获取每个组的数据,并为任何子组重复。我提出的解决方案使用递归从第一个请求中获取数据并将嵌套属性添加到原始数组:
fetch("/mygroups")
.then((res) => res.json())
.then((data) => {
return data.map((group) => ({ value: group.id, label: group.name, children: [] }));
})
.then((groups) => {
groups.forEach((group) => {
fetchGroupData(group);
});
return groups;
})
.then((groups) => {
// I need this groups variable to be the final groups variable with all it's
// nested children
functionToCallAfterAllRequestsAreMade(groups);
});
async function fetchGroupData(group) {
const res = await fetch(`/groups/${group.value}`);
const data = await res.json();
// A group can have locations and/or more groups as its children.
// if it has groups, it will call fetchGroupData for those
// child groups
const locations = data.locations.map((location) => ({
value: location.id,
label: location.location_name,
}));
const groups = data.groups.map((group) => ({
value: group.id,
label: group.name,
children: [],
}));
group.children = [...groups, ...locations];
if (groups.length > 0) {
group.children.forEach((child) => {
if (child.hasOwnProperty("children")) {
fetchGroupData(child);
}
});
}
}
问题在于,此代码似乎为初始组数组调用 fetchGroupData 并添加其子级,但随后仅返回一层深,而无需等待下一层调用继续进行。 fetchGroupData 函数不断被调用正确的次数,但由于某种原因,我只能从第一轮调用中访问数组。我怎样才能等到所有电话都完成?我已经尝试在任何地方添加一堆等待,甚至使用 promise.all 作为 forEach 没有运气。此外,如果有一种完全不同的方法来解决这个格式问题,这会更容易,那也将不胜感激。谢谢。
【问题讨论】:
-
你能发布一个 JSON 的例子吗?不是整个事情,就像几个分支一样。
标签: javascript asynchronous recursion async-await promise