首页 > 解决方案 > 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)检索所有条目,直到最后一个孩子(没有进一步的记录)?

标签: javascriptapirecursionpromiseaxios

解决方案


使用手动堆栈处理递归可能是最简单的。

由于这是一个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;
}

)


推荐阅读