How to avoid multiple nested XHRs?
I'm finding myself progressively caught up in XHR loops when building dynamic windows/tables eg:
var xhr1 = Titanium.Network.createHTTPClient();
xhr1.onload = function()
{
var xhr1JSON = JSON.parse(this.responseText);
var xhr2 = Titanium.Network.createHTTPClient();
xhr2.onload = function()
{
var xhr2JSON = JSON.parse(this.responseText);
var xhr3 = Titanium.Network.createHTTPClient();
xhr3.onload = function()
{
var xhr3JSON = JSON.parse(this.responseText);
}
xhr3.open();
xhr3.send();
}
xhr2.open();
xhr2.send();
}
xhr1.open();
xhr1.send();
If each of the JSON variables rely on the previous XHR request for their data, it seems like this continuous nesting is the only way to go. But it's getting awfully complicated in my project and I'm starting to get warnings about functions within functions.
Ideally I'd like to have one function that runs an XHR request and returns the response to a (hopefully, global) variable, but can't find similar examples.
Any suggestions would be most appreciated- thanks!
2 Answers
-
That's because you're using anonymous functions instead of named ones.
You can also call http requests synchronously, though I have not tried that personally.
-
This looks like it's exactly what I'm after:
http://bradvernon.com/2010/03/titanium-mobile-synchronous-network-request-workaround/