Dealing with Recursive Promises in a Hierarchical Data Structure
I am facing flow-control challenges within my application. I am working with a nested data structure that resembles a family tree, for example:
{name: "Bob", children: [{name: "Tim", children: [..]}, {another child..}]}
This structure can have multiple levels of depth.
My goal is to recursively traverse all individuals, obtain their ID, and make an API call to fetch their respective pictures.
Pseudo code snippet:
gatherPicture(hierarchy);
console.log("I want to wait before doing this!") // Logs too early
function gatherPicture(person) {
// api request (promise)
getPicture(person.id).then(r => {
person.picture = r;
person.children.forEach(gatherPicture);
})
}
Hopefully, the provided code snippet clarifies things. How can I ensure that my code waits until the gatherPicture function has successfully processed and resolved all individuals?
If it helps, I am using AngularJS and have access to the $q promise service. However, I am unsure how to construct this specific chain of promises due to them being created within a recursive function.
Thank you!