【问题标题】:Traversing and build Tree from fetched child details in NodeJS [duplicate]从NodeJS中获取的子详细信息遍历和构建树[重复]
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 还是一样的问题,和foreach一样
  • 您的示例预期结果未显示 user.text.title 属性。这会导致传递给 getUserTree 函数的 id 未定义。您还需要在地图中返回 getUserTree 的结果
猜你喜欢
  • 1970-01-01
  • 2011-03-25
  • 1970-01-01
  • 2015-06-16
  • 2010-11-02
  • 1970-01-01
  • 2016-10-22
  • 2015-01-10
  • 1970-01-01
相关资源
最近更新 更多