关于javascript:递归异步请求生成目录树

52次阅读

共计 2345 个字符,预计需要花费 6 分钟才能阅读完成。

前端递归异步生成目录树

需要,给出一个根节点 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}]}]}]}]}

正文完
 0