gpt4 book ai didi

javascript - 从 NodeJS 中获取的子详细信息遍历并构建树

转载 作者:太空宇宙 更新时间:2023-11-04 01:34:10 24 4
gpt4 key购买 nike

我试图通过遍历给定的 ID 并将其子级附加到树来构建树结构。它总是分配 user.children = 'sample' 而不是从 user.children = usrChild 获取用户子级,也尝试过 usrArr[index].children = 'sample'

我想要实现的目标:使用用户ID,我将获取它的 child ,现在对于每个 child ,我将获取他们的 child ,直到没有 child 留下。

函数 UserProfile.getUserChildren 返回一个包含所有子项的数据的 promise 。现在,我们迭代每个 child 并获取他们的 child

视觉上预期的输出:

enter image description here

以编程方式我期待什么:

[
{
text: {
userID: 1
name: 'Mike'
},
children:[
{
text: {
userID: 2
name: 'John'
},
children [
{
text: {
userID: 4
name: 'Hero'
},
children []
}
]
},
{
text: {
userID: 3
name: 'Kelvin'
},
children []
}

]
}
]

Node JS 中的代码:

let UserProfile = require('./UserProfile');

// Love Dad 83273010
let userID = 51405009;
var allDistributors = Array();
rootUser = new Object();
rootUser.text = {userID:userID,name:'Root'};
rootUser.children = [];
function getUserTree(userID){
return new Promise( (resolve,reject) => {
/*
* UserDownline Return User child Array
* Format:
* [
* { text: {
* userID: 45
* name: 'Mike'
* },
* children:[]
* }
* ]
*
*/
UserProfile.getUserChildren(userID).then(async (data) => {
if(data.length > 0){
rootUser.children = data;
/*
* Iterating each user to fetch and assign its child
*/
await rootUser.children.forEach(async (user,index,usrArr) => {

user.children = 'sample'

await getUserTree(user.text.title).then( async(usrChild) => {
/*
Assigning child to root user
*/
usrArr[index].children = usrChild; // STILL NOT ABLE TO ASSIGN VALUE and return user.children as 'sample'
}).then(resolve(rootUser));



});
//resolve(rootUser)
//console.log(rootUser)
//return Promise.all(rootUser);
}else
resolve([]); // return empty child when no child exist
});
//return rootUser.children;

//console.log(rootUser);
});


}
//console.log(JSON.stringify(rootUser));
getUserTree(userID).then((data) => {
console.log(JSON.stringify(data));
});

最佳答案

正如 Jaromanda X 所指出的,rootUser.children.foreach 返回未定义而不是 promise 。考虑使用 rootUser.children.map 代替。这会返回一个 Promise 数组,您可以使用 Promise.all 等待它。 ,它返回一个数组的 promise 。由于map不会修改原始数组,因此您需要将rootUser.children分配给Promise.all

的等待结果

关于javascript - 从 NodeJS 中获取的子详细信息遍历并构建树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55074994/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com