JavaScript递归调用Axios.get [英] JavaScript Recursively call Axios.get
问题描述
我有一个API,该API返回具有多个记录的父子关系
I have an API that returns a Parent Child relationship with multiple records
第一次调用API http://someAPI/getResult/?parent = null会给我:
First call to API http://someAPI/getResult/?parent=null will give me:
{
ParentID: null,
Id: 1,
Name: 'Top Level Element'
}
第二个调用应该是http://someAPI/getResult/?parent = 1,它将返回:
Second call should be to http://someAPI/getResult/?parent=1 and that will return:
[
{
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.那些人将返回自己的孩子,直到最终没有孩子返回.
The next should be http://someAPI/getResult/?parent=2 and then http://someAPI/getResult/?parent=3. Those will return their own children until finally no children are returned.
我如何编写一个递归函数,该函数将从顶层(ParentID = null)直到最后一个孩子(没有其他记录)检索所有条目?
How can I write a recursive function that will retrieve all entries from the top level (ParentID = null) until the last child (no further records)?
推荐答案
使用手动堆栈处理递归可能最简单.
It might be simplest to handle the recursion with a manual stack.
由于这是一个 async
函数,它将返回一个Promise,该Promise最终将解析为一个包含每个 parent =
...
As this is an async
function, it will return a Promise that should eventually resolve to an object containing the responses for each 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;
}
(另一种使用实际递归函数调用的公式:
(Another formulation that uses actual recursive function calls:
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;
}
)
这篇关于JavaScript递归调用Axios.get的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!