JavaScript递归调用Axios.get
我有一个API,它返回具有多条记录的父子关系 对API的第一次调用http://someAPI/getResult/?parent=null 将给我:JavaScript递归调用Axios.get,javascript,api,recursion,promise,axios,Javascript,Api,Recursion,Promise,Axios,我有一个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 Ele
{
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 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;
}
相互递归是构建树的好方法- const fetchJson=url==> fetchurl.thenr=>r.json const getResult=parent=null=> fetchJson`http://someAPI/getResult/?parent=${parent}` .thenchildren=>Promise.allchildren.mapgetResultAux//
{…t,孩子们:等待getResultt.id}//太棒了。我选择了第二种选择。一个小的变化是您不将结果传递给populateResults函数,而只传递id。
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;
}
[
{
parentId: null,
id: 1,
name: 'Top Level Element',
children:
[
{
parentId: 1,
id: 2,
name: 'Second Level Element First Element',
children: [ { ... }, { ... }, ... ]
},
{
parentId: 1,
id: 3,
name: 'Second Level Element Second Element',
children: [ ... ]
}
]
}
]