我试图通过遍历给定的ID并将其子代附加到树上来构建树结构。它总是分配 user.children ='sample',而不是从 user.children = usrChild 获取的用户子级,也尝试了 usrArr [index] .children ='sample '
我要实现的目标: 使用userID,我将获取其子项,现在对于每个子项,我将获取其子项,直到没有子项为止。
函数UserProfile.getUserChildren返回包含所有子项的数据的Promise。 现在,我们迭代每个孩子并提取他们的孩子
视觉上预期的输出:
从程序上我期望什么:
[
{
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));
});
答案 0 :(得分:0)
正如Jaromanda X指出的,rootUser.children.foreach
返回undefined而不是promise。考虑改用rootUser.children.map
。这将返回一个可以使用Promise.all
等待的Promises数组,它返回一个数组的Promise。由于map不会修改原始数组,因此您需要将rootUser.children
分配给Promise.all