How to Work with Asynchronous Functions Recursively

asyncrecursion

I am currently working on FLEX and have to call a web services. once I have the result, I have to call the web service again, with the previous result as the input.

A compounding problem, is that the service might return multiple results, and I have to call the service again with each of the results as the input. Lastly, i need the results to be in a hierarchical array collection, with each result as the child of the input to the web service.

If it were a synchronous function, it would have been very easy, but I have spent half a day trying to come up with something elegant for the web service.

I ended up with having two arrays, one for the input, and one for the results. Every time I had one or more result, I would put it in the Input array and the results. I would then remove the first item from the input array and call the web service with it, and so on, till I finished all the inputs. Once I had all the results, I made a recursive function that would create the hierarchical tree, that I needed.

This seems like a very hacky, WTF Solution. Is there any elegant and better solution? I am all ears.

Best Answer

Maybe you could implement some sort of "auto-loading tree".

Start with the first node. This node fetches data from server. For each item found in the response, it creates a child node that will load the appropriate data. And so on...

One thing you need to know is "When is it complete ?"

This can be handled with events. Each node send an event up when all its children are complete. Recursively this will end up telling the root that all is children are complete. The root node will fire the "I'm complete" event to tell whoever wants to know it, that the tree is complete.

However, I'm wondering : why don't you create a service on the server that returns the whole tree ?