递归异步请求生成目录树

前端递归异步生成目录树

需求,给出一个根节点id,每个节点都会发起异步请求,递归生成目录树

let queryTreeById = async (entityId = '') => {
  let result = await httpRequst({
    method: "GET",
    path: "/admin/******?entityId=" + entityId
  })
  //树状格式
  let tree = result.map(({code, entityId, parentId, hasChild}) => ({code, entityId, parentId, hasChild}))
  return tree
}
function loadTree(item,result){//item 当前节点信息,result是对象 进行存储树结构数据
  return new Promise((resolve,reject)=>{
    if(item.hasChild){//需要异步加载节点
      queryTreeById(item.entityId).then(list=>{
        result['children']=list
        let arr=[]
        list.forEach((item,index) => {
          arr[index]=loadTree(result['children'][index],result['children'][index])
        });
        Promise.all(arr).then(values=>{
          return resolve(values)
        })
      })
    }else{//子节点不需要异步加载 结束此子节点
      return resolve(result)
    }
  })
}
let obj={//最终结果  用来装载数据
  children: []
}
let rootInfo={entityId:134267,hasChild:true}//根节点信息
loadTree(rootInfo,obj).then(()=>{
  console.log('请求结束')
  console.log(JSON.stringify(obj))
})

输出结果

请求结束
{"children":[{"code":"表管理","entityId":134254,"parentId":134267,"hasChild":false},{"code":"test","entityId":134255,"parentId":134267,"hasChild":false},{"code":"油站","entityId":134275,"parentId":134267,"hasChild":true,"children":[{"code":"油站","entityId":134276,"parentId":134275,"hasChild":true,"children":[{"code":"管嘴信息表","entityId":134277,"parentId":134276,"hasChild":false}]}]},{"code":"盘车装置电动机","entityId":134278,"parentId":134267,"hasChild":true,"children":[{"code":"管嘴信息表","entityId":134279,"parentId":134278,"hasChild":false}]},{"code":"墙","entityId":134268,"parentId":134267,"hasChild":true,"children":[{"code":"基本墙","entityId":134269,"parentId":134268,"hasChild":true,"children":[{"code":"dsdds","entityId":134270,"parentId":134269,"hasChild":true,"children":[{"code":"hggj","entityId":134271,"parentId":134270,"hasChild":false},{"code":"hggj2","entityId":134272,"pachildren":[{"code":"管嘴信息表","entityId":134277,"parentId":134276,"hasChild":false}]}]},{"code":"盘车装置电动机","entityId":134278,"parentId":134267,"hasChild":true,"children":[{"code":"管嘴信息表","entityId":134279,"parentId":134278,"hasChild":false}]},{"code":"墙","entityId":134268,"parentId":134267,"hasChild":true,"children":[{"code":"基本墙","entityId":134269,"parentId":134268,"hasChild":true,"children":[{"code":"dsdds","entityId":134270,"parentId":134269,"hasChild":true,"children":[{"code":"hggj","entityId":134271,"parentId":134270,"hasChild":false},{"code":"hggj2","entityId":134272,"parentId":134270,"hasChild":false}]}]}]}]}

你可能感兴趣的:(递归异步请求生成目录树)