I have a recursive function that makes asynchronous calls, using the results of those calls as arguments for subsequent recursive calls.
I am trying to find a way to wait for all recursion levels to complete simultaneously, without any delays at each level. This means that all recursions should run in parallel, followed by a final cleanup step.
To illustrate my goal, let's consider a family tree API scenario where I fetch my own record which may contain information about parents. If it does, I want to recursively fetch parent records and continue up the family tree.
These requests will be made concurrently with varying start times, and they might take different lengths of time to return. However, I need to ensure that all records are fetched before moving on to the 'Cleanup' phase.
const recurse = (url) => {
console.log('Recurse: ', url)
fetch(url).then((res) => {
db.write(res.json)
if ('parents' in res.json) {
for (let parent of Object.values(res.json.parents)) {
recurse(parent.URL)
}
}
})
}
}
const main = () => {
let data = 'http://api.familytree.example.com/me'
console.log('Start')
recurse(data)
console.log('Cleanup')
}
main()