Traversing javascript promises tree

2019-03-06 02:10发布

问题:

I am new to javascript promises and tried to solve the subsequent problem:

There is a tree with nodes that have a structure like this

node: {id, children:node[]}

one node is received by calling

getNode(id)

where getNode returns a javascript promise

so I get one node object by

getNode(id).then(function(node) {
   id = node.id;
   children = node.children;

})

Now I want to get the whole tree in one object like

treeObject = getTree(rootNodeId)

so that in the end contents of treeObjects should be for example

 {1,children:
         [{2,children
              [{5,null},{6,null},{7,null]},
           {3,children[{8,null},{9,null]}...

??? thanks for any answers!

回答1:

async function getTree ( id ){
  const node = await getNode(id);
  node.children = await Promise.all( node.children.map(getTree));
  return node;
}

or without async await:

 function getTree ( id ){
  return getNode(id).then(function(node){
   return Promise.all( node.children.map(getTree)).then(function(children){
      node.children = children;
      return node;
   });
 });
}

assuming that children is a list of ids