【发布时间】:2019-03-09 18:52:28
【问题描述】:
我正在尝试通过遍历给定 ID 并将其子项附加到树来构建树结构。它总是分配 user.children = 'sample' 而不是从 user.children = usrChild 获取用户子级,还尝试了 usrArr[index].children = 'sample '
我正在尝试实现的内容: 使用用户 ID,我将获取其孩子,现在对于每个孩子,我将获取他们的孩子,直到没有孩子为止。
function UserProfile.getUserChildren 返回一个包含所有子项的数据的承诺。 现在,我们迭代每个孩子并获取他们的孩子
视觉预期输出:
以编程方式我的期望:
[
{
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));
});
【问题讨论】:
-
await xxx.forEach(async- 这并不像你认为的那样......因为forEach(立即)返回undefined,forEach 回调中的任何内容都不是awaited on -
知道如何实现它或任何其他迭代方式,因此在 getUserTree 完成后执行分配?
-
Array.map 和 promise.all
标签: javascript node.js promise es6-promise