javascript - JavaScript 递归调用 Axios.get
问题描述
我有一个返回具有多条记录的父子关系的 API
第一次调用 API http://someAPI/getResult/?parent=null 会给我:
{
ParentID: null,
Id: 1,
Name: 'Top Level Element'
}
第二次调用应该是 http://someAPI/getResult/?parent=1 ,这将返回:
[
{
ParentID: 1,
ID: 2,
Name: 'Second Level Element First Element'
},
{
ParentID: 1,
ID: 3,
Name: 'Second Level Element Second Element'
}
]
下一个应该是 http://someAPI/getResult/?parent=2,然后是 http://someAPI/getResult/?parent=3。那些将返回他们自己的孩子,直到最终没有孩子被返回。
如何编写一个递归函数,从顶层(ParentID = null)检索所有条目,直到最后一个孩子(没有进一步的记录)?
解决方案
使用手动堆栈处理递归可能是最简单的。
由于这是一个async
函数,它将返回一个 Promise,该 Promise 最终应该解析为一个包含每个响应的对象parent=
......
async function getTree() {
const idsToCheck = ["null"];
const results = {};
while (idsToCheck.length) {
const id = idsToCheck.shift();
if (results[id]) {
// We've already processed this node
continue;
}
const resp = await fetch("http://someAPI/getResult/?parent=" + id);
if (!resp.ok) throw new Error("response not ok");
const data = await resp.json();
results[id] = data;
data.forEach((child) => {
idsToCheck.push(child.Id);
});
}
return results;
}
(另一个使用实际递归函数调用的公式:
async function getTree() {
const results = {};
async function populateResults(id) {
if (results[id]) {
// We've already processed this node
return;
}
const resp = await fetch("http://someAPI/getResult/?parent=" + id);
if (!resp.ok) throw new Error("response not ok");
const data = await resp.json();
results[id] = data;
for (let child of data) {
await populateResults(results, child.Id);
}
}
await populateResults("null");
return results;
}
)
推荐阅读
- java - 如何使用 Java 中的 Selenium 在 Firefox 中使用自创扩展处理代理身份验证?
- css - 媒体查询和高度问题
- swift - 为什么函数调用需要参数名称,而分配给变量的函数却不允许?
- java - 如何在 Java 中使用 HTTP/REST 交换访问令牌(Oauth 2.0)的授权码?
- python - 如果前一列中的值不同,则计数器会增加,但在其他列值更改时会重置?
- mysql - 从 MySQL 视图中选择
- javascript - 可查看的内容会在设定的时间间隔内发生变化 - 但之前的内容会在之后闪现
- r - 将“绘制”标签保持在 ggplot2 的范围内
- python - 网页开发模板
- r - 使用循环 1 测试素数:sqrt(x)