This program is written using ReactJS and REST API is used to get the data. The problem I am facing is that I am trying to traverse a tree of data and I need to make an async request for each node in the tree.
The tree looks something like this: example tree
Currently, my code traverses the tree in breadth-first order, and the order looks like: 1->2->3->4->4. I need it to traverse the tree in depth-first order, so that the order is 1->3->4->2->4. The goal is to make an API request for each node in depth-first order and push the results into an array.
The data we start off with is an array, [node1, node2], and the result array should be [node1, node3, node4, node2, node4].
The issue is that the async nature of the method allows the code to move to node 2 before we've even traversed and pushed the child data for node 1 into our resulting array. Before we've completely traversed all possible children for node1, it's already moving on to node2 and pushing that into our result array, and then going on to process it as well. Here is an example of what the code looks like currently:
var resultArray = [];
getNodes(nodesArray) {
nodesArray.forEach(node => {
//Store nodes
resultArray.push(node)
//make a new request
const newRequest = node.id;
//our async request
getNodeData(newRequest)
.then((data) => {
var childNodes = data.nodes;
//Call method again for child nodes
this.getNodes(childNodes);
})
.catch((error) => {
console.log(error)
})
})
}
I have tried using Promises to await for the data to come in, but no luck in getting the .forEach loop to actually wait before moving onto the next node.
You can make the function async
, then use await
with a for ... of
loop.
async getNodes(nodesArray) {
for (const node of nodesArray) {
resultArray.push(node)
const newRequest = node.id;
try {
const res = await getNodeData(newRequest);
const childNodes = res.nodes;
await this.getNodes(childNodes);
} catch (error) {
console.log(error);
}
})
}